<template>
  <div class="chat-page">
    <!-- 上方内容区域 -->
    <div class="chat-main">
      <!-- 左侧知识库选择区域 -->
      <div class="chat-left" v-show="searchSources.includes('personal') || searchSources.includes('enterprise')">
        <div class="knowledge-selector">
          <!-- 知识库分类标题 -->
          <div class="knowledge-title">
            <div class="title-line"></div>
            <span>知识库分类</span>
          </div>
        
          
          <!-- 知识库类型Tab页 -->
          <div v-if="searchSources.includes('personal') || searchSources.includes('enterprise')" class="knowledge-tabs">
            <template v-if="searchSources.includes('enterprise') && searchSources.includes('personal')">
              <!-- 同时选择了企业和个人知识库，显示Tab页 -->
              <div class="tab-buttons">
                <button
                  class="tab-button"
                  :class="{ active: activeKnowledgeTab === 'enterprise' }"
                  @click="activeKnowledgeTab = 'enterprise'"
                >
                  企业知识库
                  <span v-if="selectedEnterpriseKnowledge.length > 0" class="tab-badge">{{ selectedEnterpriseKnowledge.length }}</span>
                </button>
                <button
                  class="tab-button"
                  :class="{ active: activeKnowledgeTab === 'personal' }"
                  @click="activeKnowledgeTab = 'personal'"
                >
                  个人知识库
                  <span v-if="selectedPersonalKnowledge.length > 0" class="tab-badge">{{ selectedPersonalKnowledge.length }}</span>
                </button>
              </div>
            </template>
            <template v-else>
              <!-- 只选择了一种知识库，显示类型指示器 -->
              <div class="knowledge-type-indicator">
                <span class="type-label">
                  {{ searchSources.includes('enterprise') ? '企业知识库' : '个人知识库' }}
                </span>
              </div>
            </template>
          </div>
          
          <!-- 搜索框 -->
          <div class="knowledge-search">
            <input
              type="text"
              placeholder="输入分类搜索"
              class="knowledge-search-input"
              v-model="searchKeyword"
              @input="handleSearch"
              @keyup.enter="handleSearch"
            >
            <button v-if="!searchKeyword" class="knowledge-search-btn" @click="handleSearch">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
              </svg>
              搜索
            </button>
            <button v-else class="knowledge-search-btn clear-btn" @click="clearSearch">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
              清除
            </button>
          </div>
           <!-- 选择操作按钮 -->
          <div class="selection-controls">
            <div class="select-all-wrapper">
              <div 
                class="select-all-checkbox"
                :class="{ checked: isAllSelected }"
                @click="toggleSelectAll"
              >
                <el-icon v-if="isAllSelected">
                  <Check />
                </el-icon>
              </div>
              <span class="select-all-text" @click="toggleSelectAll">全选</span>
            </div>
            
            <span class="selected-count">
              <template v-if="searchSources.includes('enterprise') && searchSources.includes('personal')">
                已选 {{ selectedKnowledge.length }} 项 (总计: {{ selectedEnterpriseKnowledge.length + selectedPersonalKnowledge.length }} 项)
              </template>
              <template v-else>
                已选 {{ selectedKnowledge.length }} 项
              </template>
            </span>
            
            <span 
              class="clear-selection" 
              @click="clearSelection"
              :class="{ disabled: selectedKnowledge.length === 0 }"
            >
              清除选择
            </span>
          </div>
          
          <!-- 知识库分类列表 -->
          <div class="knowledge-categories">
            <div
              v-for="category in knowledgeCategories"
              :key="category.id"
              class="knowledge-category"
            >
              <div class="category-title" @click="toggleCategory(category.id)">
                <span class="category-icon">{{ category.icon }}</span>
                <span>{{ category.name }}</span>
                <el-icon v-if="category.children && category.children.length > 0" class="expand-icon" :class="{ expanded: expandedCategories.includes(category.id) }">
                  <ArrowRight />
                </el-icon>
              </div>

              <!-- 子分类列表 - 无限层级递归 -->
              <div v-if="expandedCategories.includes(category.id) && category.children" class="category-list">
                <TreeNode
                  v-for="item in category.children"
                  :key="item.id"
                  :node="item"
                  :level="1"
                  :selected-knowledge="selectedKnowledge"
                  :expanded-items="expandedItems"
                  @toggle-knowledge="toggleKnowledge"
                  @toggle-expand="handleToggleExpand"
                  @toggle-parent="toggleParentSelection"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧聊天区域 -->
      <div class="chat-right" :class="{ 'full-width': !searchSources.includes('personal') && !searchSources.includes('enterprise') }">
        
        <div class="chat-content" ref="chatContentRef">
          <div v-if="messages.length === 0" class="chat-welcome">
            <div class="welcome-avatar">
              <img src="@/assets/十一建logo/1.gif" alt="智能助手" class="avatar-gif" />
            </div>
            <div class="welcome-text">
              <h3>Hello,张三</h3>
              <p>我可以回答各种问题，请把你的问题交给我！</p>
            </div>
            
            <div class="quick-questions">
              <div class="question-row">
                <button class="quick-question" @click="askQuestion('1.企业办了哪些证001')">
                  1.企业办了哪些证001
                </button>
                <button class="quick-question" @click="askQuestion('2.企业办了哪些证002')">
                  2.企业办了哪些证002
                </button>
              </div>
              <div class="question-row">
                <button class="quick-question" @click="askQuestion('3.企业办了哪些证003')">
                  3.企业办了哪些证003
                </button>
                <button class="quick-question" @click="askQuestion('4.企业办了哪些证004')">
                  4.企业办了哪些证004
                </button>
              </div>
            </div>
          </div>
          
          
          <!-- 消息列表 -->
          <div v-for="message in messages" :key="message.time" class="message" :class="message.type">
            <div class="message-avatar">
              <img v-if="message.type === 'assistant'" src="@/assets/十一建logo/1.gif" alt="AI助手" class="avatar-gif" />
              <div v-else class="user-avatar">{{ getCurrentUserAvatar() }}</div>
            </div>
            <div class="message-content">
              <!-- AI消息完成标识 -->
              <div v-if="message.type === 'assistant'" 
                   class="ai-status" 
                   :class="{ 'error': message.hasError, 'thinking': message.isStreaming }"
                   :style="message.hasError ? 'background: rgba(239, 68, 68, 0.08) !important; color: #ef4444 !important; border: 1px solid rgba(239, 68, 68, 0.15) !important;' : ''">
                <span class="status-icon">
                  {{ message.hasError ? '✗' : (message.isStreaming ? '⌛' : '✓') }}
                </span>
                <span class="status-text">
                  {{ message.hasError ? '思考发生异常' : (message.isStreaming ? '正在思考' : '已完成思考') }}
                </span>
              </div>
              <!-- 翻译状态指示器 -->
              <div v-if="message.isTranslated" class="translation-indicator">
                <svg viewBox="0 0 24 24" width="14" height="14" fill="#4285f4">
                  <path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
                </svg>
                <span>已翻译</span>
              </div>
              <div class="message-text" v-html="getRenderedContent(message.content)"></div>

              <!-- 显示消息中的文件 -->
              <div v-if="message.files && message.files.length > 0" class="message-files">
                <div v-for="file in message.files" :key="file.id" class="message-file-tab">
                  <div class="message-file-icon">
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="#4285f4">
                      <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                    </svg>
                  </div>
                  <div class="message-file-content">
                    <div class="message-file-title">{{ getFileDisplayName(file.name) }}</div>
                    <div class="message-file-url">{{ file.name }}</div>
                  </div>
                  <div class="message-file-size">{{ formatFileSize(file.size) }}</div>
                </div>
              </div>

              <!-- 消息操作按钮 -->
              <div v-if="message.type === 'assistant'" class="message-actions">
                <button @click="copyMessage(message.content)" class="action-btn" title="复制">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="downloadMessage(message.content)" class="action-btn" title="下载">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="expandMessage(message)" class="action-btn" title="扩写">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="summarizeMessage(message)" class="action-btn" title="简写">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M19,13H5V11H19V13Z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="regenerateMessage(message)" class="action-btn" title="重新生成">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="toggleTranslation(message)"
                        class="action-btn"
                        :class="{ 'translated': message.isTranslated }"
                        :title="message.isTranslated ? '返回原文' : '翻译'">
                  <svg v-if="!message.isTranslated" viewBox="0 0 24 24" width="14" height="14">
                    <path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z" fill="currentColor"/>
                  </svg>
                  <svg v-else viewBox="0 0 24 24" width="14" height="14">
                    <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" fill="currentColor"/>
                  </svg>
                </button>
                <button @click="deleteMessage(message)" class="action-btn delete-btn" title="删除">
                  <svg viewBox="0 0 24 24" width="14" height="14">
                    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" fill="currentColor"/>
                  </svg>
                </button>
              </div>

              <!-- 搜索来源 -->
              <div v-if="message.type === 'assistant' && message.searchSources && message.searchSources.length > 0" class="search-sources">
                <div class="sources-header">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="#5b7cff">
                    <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                  </svg>
                  <span class="sources-title">基于以下搜索来源</span>
                </div>
                <div class="sources-grid">
                  <div v-for="(source, index) in (message.searchSources as SearchSource[])" :key="index"
                       class="source-card"
                       :class="getSourceCardClass(source.category)">
                    <div class="source-header">
                      <div class="source-title">{{ source.title }}</div>
                      <div v-if="source.category"
                           class="source-category"
                           :class="getSourceCategoryClass(source.category)">
                        {{ source.category }}
                      </div>
                    </div>
                    <div class="source-content">{{ source.content }}</div>
                    <div v-if="source.url" class="source-url">{{ source.url }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 打字指示器 -->
          <div v-if="isTyping" class="message assistant">
            <div class="message-avatar">
              <img src="@/assets/十一建logo/1.gif" alt="AI助手" class="avatar-gif" />
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 聊天工具栏 -->
    <div v-if="messages.length > 0" class="chat-toolbar">
      <div class="toolbar-right">
        <el-button 
          size="small" 
          @click="clearChatHistory" 
          class="clear-btn"
          title="清除聊天记录"
        >
          <el-icon><Delete /></el-icon>
          清除记录
        </el-button>
      </div>
    </div>
    
    <!-- 底部输入框区域 -->
    <div class="chat-input">
      <div class="input-container">
        <!-- 已上传文件列表 - 显示在输入框上方 -->
        <div v-if="uploadedFiles.length > 0" class="uploaded-files-inline">
          <div v-for="file in uploadedFiles" :key="file.id" class="file-tab" :class="{ 'uploading': file.uploading }">
            <div class="file-tab-icon">
              <svg v-if="!file.uploading" viewBox="0 0 24 24" width="16" height="16" fill="#4285f4">
                <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
              </svg>
              <div v-else class="uploading-spinner">
                <svg viewBox="0 0 24 24" width="16" height="16">
                  <circle cx="12" cy="12" r="3" fill="none" stroke="#4285f4" stroke-width="2" stroke-dasharray="12" stroke-dashoffset="12">
                    <animate attributeName="stroke-dashoffset" values="12;0" dur="1s" repeatCount="indefinite"/>
                  </circle>
              </svg>
              </div>
            </div>
            <div class="file-tab-content">
              <div class="file-tab-title">{{ getFileDisplayName(file.name) }}</div>
              <div class="file-tab-url">
                <span v-if="file.uploading" class="upload-status">上传中...</span>
                <span v-else-if="file.url" class="upload-status success">已上传</span>
                <span v-else class="upload-status">待上传</span>
            </div>
            </div>
            <button class="file-tab-close" @click="removeFile(file.id)" title="移除文件" :disabled="file.uploading">
              <svg viewBox="0 0 24 24" width="12" height="12">
                <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" fill="currentColor"/>
              </svg>
            </button>
          </div>
        </div>

        <div class="input-wrapper"
             @drop="handleDrop"
             @dragover="handleDragOver"
             @dragenter="handleDragEnter"
             @dragleave="handleDragLeave"
             :class="{ 'drag-over': isDragOver }">
          <textarea
            v-model="inputMessage"
            placeholder="请输入问题，Enter发送，Shift+Enter换行"
            @keyup.enter="handleEnterKey"
            @input="adjustTextareaHeight"
            ref="textareaRef"
            class="message-input"
            rows="1"
          />
          
          <div class="input-actions">
            <div class="left-actions">
              <el-select
                v-model="searchSources"
                multiple
                size="small"
                class="search-source-select"
                style="width: 160px;"
                collapse-tags
                collapse-tags-tooltip
                placeholder="选择搜索来源"
              >
                <el-option
                  v-for="option in searchSourceOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                >
                  <span style="display: flex; align-items: center;">
                    <span style="margin-right: 6px; display: inline-flex; align-items: center;">
                      <component :is="option.icon" style="width: 14px; height: 14px;" />
                    </span>
                    {{ option.label }}
                  </span>
                </el-option>
              </el-select>
              <el-select
                v-model="selectedModel"
                size="small"
                class="model-select"
                style="width: 120px; margin-left: 8px;"
              >
                <el-option
                  v-for="model in modelOptions"
                  :key="model.value"
                  :label="model.label"
                  :value="model.value"
                />
              </el-select>
            </div>
            <div class="right-actions">
              <!-- 隐藏的文件输入元素 -->
              <input
                ref="fileInputRef"
                type="file"
                multiple
                accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.xls,.xlsx,.csv"
                @change="handleFileUpload"
                style="display: none;"
              />
              <el-button
                class="upload-btn"
                size="small"
                @click="triggerFileUpload"
                title="上传文件"
                style="width: 36px; height: 36px;"
              >
                <img src="@/assets/icon/file.svg" alt="上传文件" style="width: 36px; height: 36px; border-radius: 8px; padding: 0; display: flex; align-items: center; justify-content: center;" />
              </el-button>
              <el-button
                class="send-btn"
                type="primary"
                 style="width: 36px; height: 36px; border-radius: 8px; padding: 0; display: flex; align-items: center; justify-content: center;"
                @click="isTyping ? stopGeneration() : sendMessage()"
                :disabled="isSendDisabled"
                :title="isTyping ? '停止生成' : '发送'"
              >
                <el-icon v-if="isTyping" :size="24">
                  <svg viewBox="0 0 24 24" width="24" height="24">
                      <path d="M6,6H18V18H6V6Z" fill="currentColor"/>
                    </svg>
                </el-icon>
                <el-icon v-else :size="24"><Promotion /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 知识库选择提示 -->
      <div v-if="(searchSources.includes('personal') || searchSources.includes('enterprise')) && !isKnowledgeSelectionComplete" class="knowledge-tip">
        <el-alert
          :title="getKnowledgeSelectionTip()"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 8px;"
        />
      </div>

      <div class="input-footer">
        <span class="footer-text">以上内容由AI大模型生成，请甄别后使用，请勿输入个人隐私信息</span>
      </div>
    </div>
  </div>
</template>





<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElIcon, ElButton, ElSelect, ElOption, ElMessage } from 'element-plus'
import { Promotion, Check, ArrowRight, User, OfficeBuilding, Connection } from '@element-plus/icons-vue'
import TreeNode from '@/components/TreeNode.vue'
import { refreshSidebarItems } from '@/router'
import { translateMessage, knowledgeChatCompletion } from '@/api/chat'
import { uploadFile } from '@/api/translation'
import { marked } from 'marked'
import mermaid from 'mermaid'
import { es } from 'element-plus/es/locales.mjs'

// 配置marked选项 - 支持完整的Markdown语法
marked.setOptions({
  breaks: true,        // 支持换行符转换
  gfm: true           // 支持GitHub风格的Markdown
})

// 简单的Markdown渲染函数（备用方案）
const simpleMarkdownRender = (content: string): string => {
  if (!content) return ''
  
  console.log('简单渲染函数接收到内容:', content.substring(0, 100))
  
  let result = content
  
  // 处理代码块（必须在其他替换之前）
  result = result.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  
  // 处理标题
  result = result.replace(/^### (.*$)/gim, '<h3>$1</h3>')
  result = result.replace(/^## (.*$)/gim, '<h2>$1</h2>')
  result = result.replace(/^# (.*$)/gim, '<h1>$1</h1>')
  
  // 处理列表项（简化版本）
  result = result.replace(/^- (.*)$/gim, '<li>$1</li>')
  result = result.replace(/^\d+\. (.*)$/gim, '<li>$1</li>')
  
  // 包装连续的列表项
  result = result.replace(/(<li>.*<\/li>(\n|<br>)*)+/g, (match) => {
    return '<ul>' + match + '</ul>'
  })
  
  // 处理粗体和斜体
  result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  result = result.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 处理行内代码
  result = result.replace(/`([^`\n]+)`/g, '<code>$1</code>')
  
  // 处理换行
  result = result.replace(/\n/g, '<br>')
  
  console.log('简单Markdown渲染结果:', result.substring(0, 200))
  return result
}

const username = 'Admin'
const inputMessage = ref('')
const isTyping = ref(false)
const chatContentRef = ref<HTMLElement>()
// 分别维护企业知识库和个人知识库的选择状态
const selectedEnterpriseKnowledge = ref<string[]>([])
const selectedPersonalKnowledge = ref<string[]>([])
const fileInputRef = ref<HTMLInputElement>()
const uploadedFiles = ref<UploadedFile[]>([])
const messages = ref<Message[]>([])

// EventSource 连接管理
const currentEventSource = ref<EventSource | null>(null)



// 搜索来源选择（多选）
const searchSources = ref<string[]>([])

// 当前激活的知识库Tab页
const activeKnowledgeTab = ref('enterprise')

// 搜索关键词
const searchKeyword = ref('')

// 过滤后的知识库分类
const filteredKnowledgeCategories = ref([])

// 计算当前选中的知识库（根据搜索来源类型和当前Tab页）
const selectedKnowledge = computed(() => {
  // 如果同时选择了企业和个人知识库，根据当前激活的Tab页显示
  if (searchSources.value.includes('enterprise') && searchSources.value.includes('personal')) {
    if (activeKnowledgeTab.value === 'enterprise') {
      return selectedEnterpriseKnowledge.value
    } else {
      return selectedPersonalKnowledge.value
    }
  }

  // 如果只选择了一种知识库，显示对应的选择
  if (searchSources.value.includes('enterprise')) {
    return selectedEnterpriseKnowledge.value
  }

  if (searchSources.value.includes('personal')) {
    return selectedPersonalKnowledge.value
  }

  return []
})

// 计算所有选中的知识库（用于发送消息时的验证）
const allSelectedKnowledge = computed(() => {
  const result = []
  if (searchSources.value.includes('enterprise')) {
    result.push(...selectedEnterpriseKnowledge.value)
  }
  if (searchSources.value.includes('personal')) {
    result.push(...selectedPersonalKnowledge.value)
  }
  return result
})

// 检查知识库选择是否完整
const isKnowledgeSelectionComplete = computed(() => {
  const hasEnterprise = searchSources.value.includes('enterprise')
  const hasPersonal = searchSources.value.includes('personal')

  // 如果没有选择任何知识库，返回true（不需要选择）
  if (!hasEnterprise && !hasPersonal) {
    return true
  }

  // 如果选择了企业知识库，必须有企业知识库的选择
  if (hasEnterprise && selectedEnterpriseKnowledge.value.length === 0) {
    return false
  }

  // 如果选择了个人知识库，必须有个人知识库的选择
  if (hasPersonal && selectedPersonalKnowledge.value.length === 0) {
    return false
  }

  return true
})

// 获取知识库选择提示文本
const getKnowledgeSelectionTip = () => {
  const hasEnterprise = searchSources.value.includes('enterprise')
  const hasPersonal = searchSources.value.includes('personal')
  const enterpriseSelected = selectedEnterpriseKnowledge.value.length > 0
  const personalSelected = selectedPersonalKnowledge.value.length > 0

  if (hasEnterprise && hasPersonal) {
    if (!enterpriseSelected && !personalSelected) {
      return '请在企业知识库和个人知识库中分别选择分类'
    } else if (!enterpriseSelected) {
      return '请切换到企业知识库Tab页并选择分类'
    } else if (!personalSelected) {
      return '请切换到个人知识库Tab页并选择分类'
    }
  } else if (hasEnterprise && !enterpriseSelected) {
    return '请在左侧选择企业知识库分类'
  } else if (hasPersonal && !personalSelected) {
    return '请在左侧选择个人知识库分类'
  }

  return '请在左侧选择知识库分类'
}
const searchSourceOptions = [
  { value: 'web', label: '联网', icon: Connection },
  { value: 'personal', label: '个人知识库', icon: User },
  { value: 'enterprise', label: '企业知识库', icon: OfficeBuilding },
]

// 计算属性：根据搜索来源确定是否开启联网搜索
const isWebSearch = computed(() => searchSources.value.includes('web'))

// 监听搜索来源变化，提供用户反馈
watch(searchSources, (newValue, oldValue) => {
  console.log(`搜索来源已切换到：${newValue.join(', ')}`)

  // 如果搜索来源发生变化，重新初始化展开状态
  if (oldValue && JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
    // 清除展开状态，因为不同知识库有不同的分类结构
    expandedCategories.value = []
    expandedItems.value = []

    // 重新初始化展开状态
    initializeExpandedState()

    // 提示用户
    const sourceNames = newValue.map(source => {
      const sourceMap: Record<string, string> = {
        personal: '个人知识库',
        enterprise: '企业知识库',
        web: '联网搜索'
      }
      return sourceMap[source]
    }).join(' + ')

    if (sourceNames) {
      ElMessage.info(`已切换到：${sourceNames}`)
    }
  }

  // 如果是初始加载，也需要初始化展开状态
  if (!oldValue) {
    initializeExpandedState()
  }

  // 设置默认的激活tab页
  if (newValue.includes('enterprise') && newValue.includes('personal')) {
    // 如果同时选择了企业和个人知识库，默认激活企业知识库
    if (!activeKnowledgeTab.value || (!newValue.includes(activeKnowledgeTab.value))) {
      activeKnowledgeTab.value = 'enterprise'
    }
  } else if (newValue.includes('enterprise')) {
    activeKnowledgeTab.value = 'enterprise'
  } else if (newValue.includes('personal')) {
    activeKnowledgeTab.value = 'personal'
  }
}, { deep: true })

// 计算发送按钮是否应该被禁用
const isSendDisabled = computed(() => {
  // 如果正在输入中，按钮应该可点击（用于停止生成）
  if (isTyping.value) {
    return false
  }

  // 基本条件：没有输入内容且没有文件
  const basicDisabled = !inputMessage.value.trim() && uploadedFiles.value.length === 0

  // 知识库选择条件：如果选择了个人或企业知识库，必须完整选择分类
  const knowledgeDisabled = (searchSources.value.includes('personal') || searchSources.value.includes('enterprise')) && !isKnowledgeSelectionComplete.value

  return basicDisabled || knowledgeDisabled
})

const selectedModel = ref('')
const modelOptions = [
 /*  { value: 'gpt-3.5', label: 'GPT-3.5（OpenAI）' },
  { value: 'gpt-4', label: 'GPT-4（OpenAI）' },
  { value: 'wenxin', label: '文心一言（百度）' },
  { value: 'qwen', label: '通义千问（阿里）' }, */
  { value: 'Deepseek-r1', label: 'DeepSeek' },
  // { value: 'custom', label: '自定义模型' }
]

const enterpriseOptions = ref<KnowledgeOption[]>([
  // 外部知识库选项
  { id: 'national-construction', name: '国家规范' },
  { id: 'industry-construction', name: '行业规范' },
  { id: 'local-construction', name: '地方规范' },
  { id: 'national-atlas', name: '国家图集' },
  { id: 'industry-atlas', name: '行业图集' },
  { id: 'local-atlas', name: '地方图集' },
  { id: 'electrical', name: '电气设计规范' },
  { id: 'building', name: '建筑设计规范' },
  { id: 'structure', name: '结构设计规范' },
  { id: 'heating', name: '暖通设计规范' },
  { id: 'water', name: '给排水设计规范' },

  // 内部知识库选项
  { id: 'holding-regulations', name: '控股集团制度' },
  { id: 'holding-standards', name: '控股集团标准' },
  { id: 'holding-policies', name: '控股集团办法及通知' },
  { id: 'group-regulations', name: '建工集团制度' },
  { id: 'group-standards', name: '建工集团标准' },
  { id: 'group-policies', name: '建工集团办法及通知' },

  // 十一建企业制度汇编
  { id: 'business-category', name: '经营类制度' },
  { id: 'production-category', name: '生产类制度' },
  { id: 'safety-category', name: '安全类制度' },
  { id: 'technology-achievement', name: '科技成果类制度' },
  { id: 'technical-quality', name: '技术质量类制度' },
  { id: 'business-affairs', name: '商务类制度' },
  { id: 'finance-category', name: '财务类制度' },
  { id: 'hr-management', name: '人力资源与干部管理类制度' },
  { id: 'administrative', name: '行政类制度' },
  { id: 'party-discipline', name: '党风廉政建设与纪检监察类制度' },
  { id: 'audit-category', name: '审计类制度' },
  { id: 'worker-rights', name: '职工权益保障类制度' },
  { id: 'design-category', name: '设计类制度' },
  { id: 'comprehensive-management', name: '综合管理类制度' },

  // 其他专业知识
  { id: 'enterprise-internal-control', name: '企业内部控制' },
  { id: 'standardization-manual', name: '标准化手册' },
  { id: 'process-standards-guide', name: '工艺标准指南' },
  { id: 'papers', name: '论文' },
  { id: 'patents', name: '专利' },
  { id: 'construction-methods', name: '工法' },
  { id: 'enterprise-culture-type', name: '企业文化类案例' },
  { id: 'party-innovation-type', name: '党建创新类案例' },
  { id: 'case-review-results', name: '案例复盘成果' },
  { id: 'international-building-standards', name: '国际建筑说明通用规范' }
])

const personalOptions = ref<KnowledgeOption[]>([
  // 个人学习笔记
  { id: 'personal-study-notes', name: '学习笔记' },
  { id: 'personal-project-experience', name: '项目经验总结' },
  { id: 'personal-technical-insights', name: '技术心得' },
  { id: 'personal-problem-solutions', name: '问题解决方案' },

  // 个人收藏资料
  { id: 'personal-bookmarks', name: '收藏的技术文章' },
  { id: 'personal-tutorials', name: '教程和指南' },
  { id: 'personal-tools', name: '常用工具清单' },
  { id: 'personal-templates', name: '模板和示例' },

  // 个人工作记录
  { id: 'personal-daily-logs', name: '工作日志' },
  { id: 'personal-meeting-notes', name: '会议记录' },
  { id: 'personal-task-tracking', name: '任务跟踪' },
  { id: 'personal-performance-review', name: '绩效总结' },

  // 个人技能发展
  { id: 'personal-skill-assessment', name: '技能评估' },
  { id: 'personal-learning-plan', name: '学习计划' },
  { id: 'personal-certification', name: '证书和认证' },
  { id: 'personal-career-planning', name: '职业规划' }
])

interface SearchSource {
  title: string
  content: string
  url?: string
  category?: string
}

interface Message {
  type: 'user' | 'assistant'
  content: string
  time: string
  files?: UploadedFile[]
  searchSources?: string[] | SearchSource[]  // 用户消息：搜索源标识符数组 ['personal', 'enterprise', 'web']；助手消息：搜索结果来源
  enterpriseKnowledgeData?: Array<{id: string, name: string}>  // 选择的企业知识库分类列表
  personalKnowledgeData?: Array<{id: string, name: string}>    // 选择的个人知识库分类列表
  originalContent?: string  // 保存原文内容
  isTranslated?: boolean    // 标记是否已翻译
  hasError?: boolean       // 标记是否有错误
  isStreaming?: boolean    // 标记是否正在流式输出
}

interface KnowledgeOption {
  id: string
  name: string
}

interface UploadedFile {
  id: string
  name: string
  size: number
  type: string
  file: File
  url?: string     // 上传后的文件URL
  uploading?: boolean  // 是否正在上传
}

function triggerFileUpload() {
  console.log('点击上传按钮，fileInputRef:', fileInputRef.value) // 调试用
  if (fileInputRef.value) {
    fileInputRef.value.click()
  } else {
    console.error('fileInputRef 未找到')
  }
}
// 处理拖拽悬停
function handleDragOver(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = true
}

function handleDragEnter(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = true
}

function handleDragLeave(event: DragEvent) {
  event.preventDefault()
  // 只有当离开整个输入区域时才设置为false
  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const x = event.clientX
  const y = event.clientY
  
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    isDragOver.value = false
  }
}

function handleFileUpload(event: Event) {
  console.log('文件上传事件触发') // 调试用
  const target = event.target as HTMLInputElement
  const files = target.files
  
  if (files && files.length > 0) {
    console.log('选择的文件:', files) // 调试用
    Array.from(files).forEach(file => {
      // 验证文件大小 (10MB限制)
      if (file.size > 10 * 1024 * 1024) {
        ElMessage.error(`文件 ${file.name} 大小超过10MB限制`)
        return
      }
      
      // 验证文件类型 - 支持doc/docx/pdf/xlsx/csv/text/image（不含gif）
      const allowedTypes = [
        'application/pdf',                                                                    // PDF
        'application/msword',                                                                 // DOC
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',          // DOCX
        'text/plain',                                                                        // TXT
        'image/jpeg',                                                                        // JPEG
        'image/jpg',                                                                         // JPG
        'image/png',                                                                         // PNG
        'application/vnd.ms-excel',                                                          // XLS
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',               // XLSX
        'text/csv'                                                                          // CSV
      ]
      
      if (!allowedTypes.includes(file.type)) {
        ElMessage.error(`不支持的文件类型: ${file.name}`)
        return
      }
      
      const uploadedFile: UploadedFile = {
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        name: file.name,
        size: file.size,
        type: file.type,
        file: file,
        uploading: false  // 初始状态为未上传
      }
      uploadedFiles.value.push(uploadedFile)
      console.log('文件添加成功:', uploadedFile) // 调试用
    })
    
    ElMessage.success(`成功添加 ${files.length} 个文件`)
  }
  
  // 清空文件输入框
  if (target) {
    target.value = ''
  }
}

// 上传文件到服务器
async function uploadFileToServer(uploadedFile: UploadedFile): Promise<void> {
  try {
    console.log('开始上传文件到服务器:', uploadedFile.name)
    
    // 调用上传接口，使用'translate'作为prefix
    const response: any = await uploadFile(uploadedFile.file, 'translate')
    
    if (response.file_url) {
      // 更新文件对象，添加服务器返回的URL
      const fileIndex = uploadedFiles.value.findIndex(f => f.id === uploadedFile.id)
      if (fileIndex !== -1) {
        uploadedFiles.value[fileIndex].url = response.file_url
        uploadedFiles.value[fileIndex].uploading = false
        console.log('文件上传成功:', response.file_url)
      }
    } else {
      throw new Error('上传失败')
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    
    // 标记上传失败
    const fileIndex = uploadedFiles.value.findIndex(f => f.id === uploadedFile.id)
    if (fileIndex !== -1) {
      uploadedFiles.value[fileIndex].uploading = false
    }
    
    throw error // 重新抛出错误，让调用者处理
  }
}

// 添加文件到上传列表
function addFileToUpload(file: File) {
  // 验证文件大小
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error(`文件 ${file.name} 大小超过10MB限制`)
    return
  }
  
  const uploadedFile: UploadedFile = {
    id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
    name: file.name,
    size: file.size,
    type: file.type,
    file: file,
    uploading: false
  }
  uploadedFiles.value.push(uploadedFile)
}

const isDragOver = ref(false)

function handleDrop(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = false
  
  const files = event.dataTransfer?.files
  if (files) {
    Array.from(files).forEach(file => {
      addFileToUpload(file)
    })
    
    if (files.length > 0) {
      ElMessage.success(`成功拖拽 ${files.length} 个文件`)
    }
  }
}

function removeFile(fileId: string) {
  const index = uploadedFiles.value.findIndex(file => file.id === fileId)
  if (index > -1) {
    uploadedFiles.value.splice(index, 1)
    ElMessage.success('文件已移除')
  }
}

function isImageFile(file: UploadedFile): boolean {
  return file.type.startsWith('image/')
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

function getFileDisplayName(fileName: string): string {
  // 移除文件扩展名，只显示文件名
  const lastDotIndex = fileName.lastIndexOf('.')
  if (lastDotIndex > 0) {
    return fileName.substring(0, lastDotIndex)
  }
  return fileName
}

// 当前会话的时间戳，用于保持同一会话内消息时间一致
let currentSessionTimestamp = new Date().getTime().toString()

function getCurrentTime() {
  // 返回当前会话的时间戳，确保同一会话内所有消息时间一致
  return currentSessionTimestamp
}

// 获取当前会话的session_stamp
function getCurrentSessionStamp() {
  return currentSessionTimestamp
}

function clearChatHistory() {
  // 清除所有聊天记录
  messages.value = []
  
  // 重置会话时间戳为当前时间
  currentSessionTimestamp = new Date().getTime().toString()
  
  // 清除文件列表
  uploadedFiles.value = []
  
  // 清除搜索来源选择
  searchSources.value = []
  
  // 清除知识库选择
  selectedEnterpriseKnowledge.value = []
  selectedPersonalKnowledge.value = []
  
  // 重置加载状态
  isTyping.value = false
  
  // 关闭当前EventSource连接
  if (currentEventSource.value) {
    currentEventSource.value.close()
    currentEventSource.value = null
  }
  
  // 如果有chatId，清除localStorage中的记录
  if (currentChatId.value) {
    localStorage.removeItem(`chat_${currentChatId.value}`)
  }
  
  // 显示成功消息
  ElMessage.success('聊天记录已清除')
  
  // 滚动到顶部
  scrollToBottom()
}


function formatDisplayTime(timeStr: string) {
  // 如果是时间戳格式，转换为可读时间
  if (/^\d+$/.test(timeStr)) {
    const date = new Date(parseInt(timeStr))
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  // 否则直接返回原时间字符串
  return timeStr
}

function scrollToBottom() {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

function askQuestion(question: string) {
  inputMessage.value = question
  sendMessage()
}

// 处理回车键事件
function handleEnterKey(event: KeyboardEvent) {
  // 如果正在生成，阻止回车发送
  if (isTyping.value) {
    event.preventDefault()
    return
  }
  
  // 检查是否按下了 Shift 键
  if (event.shiftKey) {
    // Shift+Enter 允许换行，不阻止默认行为
    return
  }
  
  // 阻止默认的换行行为，执行发送
  event.preventDefault()
  sendMessage()
}

async function sendMessage() {
  if ((!inputMessage.value.trim() && uploadedFiles.value.length === 0) || isTyping.value) return

  // 验证知识库选择
  if ((searchSources.value.includes('personal') || searchSources.value.includes('enterprise')) && !isKnowledgeSelectionComplete.value) {
    ElMessage.warning(getKnowledgeSelectionTip())
    return
  }

  // 如果有文件需要上传，先上传所有文件
  if (uploadedFiles.value.length > 0) {
    try {
      // 标记所有文件为上传中状态
      uploadedFiles.value.forEach(file => {
        file.uploading = true
      })
      
      // 上传所有文件
      const uploadPromises = uploadedFiles.value.map(file => uploadFileToServer(file))
      await Promise.all(uploadPromises)
      
      console.log('所有文件上传完成')
    } catch (error) {
      console.error('文件上传失败:', error)
      ElMessage.error('文件上传失败，请重试')
      return
    }
  }

  // 构建知识库选择数据（分别获取企业和个人知识库）
  const enterpriseKnowledgeData = getEnterpriseKnowledgeDetails()
  const personalKnowledgeData = getPersonalKnowledgeDetails()

  // 构建发送给AI的消息内容
  let messageContent = ''
  const fileUrls: string[] = []
  
  // 收集所有已上传的文件URL
  uploadedFiles.value.forEach(file => {
    if (file.url) {
      fileUrls.push(file.url)
    }
  })

  if (!inputMessage.value.trim() && uploadedFiles.value.length > 0) {
    // 用户没有输入内容，只上传了文件
    messageContent = '请解析这个文件'
    if (fileUrls.length > 0) {
      messageContent += ' ' + fileUrls.join(' ')
    }
  } else if (inputMessage.value.trim() && uploadedFiles.value.length > 0) {
    // 用户既输入了内容又上传了文件
    messageContent = inputMessage.value.trim()
    if (fileUrls.length > 0) {
      messageContent += ' ' + fileUrls.join(' ')
    }
  } else {
    // 只有用户输入，没有文件
    messageContent = inputMessage.value.trim()
  }

  const userMessage: Message = {
    type: 'user',
    content: inputMessage.value.trim() || '发送了文件',
    time: getCurrentTime(),
    files: uploadedFiles.value.length > 0 ? [...uploadedFiles.value] : undefined,
    searchSources: [...searchSources.value],
    enterpriseKnowledgeData: enterpriseKnowledgeData.length > 0 ? enterpriseKnowledgeData : undefined,
    personalKnowledgeData: personalKnowledgeData.length > 0 ? personalKnowledgeData : undefined
  }
  
  messages.value.push(userMessage)

  // 清空输入框和文件列表
  inputMessage.value = ''
  uploadedFiles.value = []

  scrollToBottom()

  // 检查是否未选择任何知识库（无知识库模式）
  const hasKnowledgeSelected = searchSources.value.includes('personal') || searchSources.value.includes('enterprise')
  
  if (!hasKnowledgeSelected) {
    // 无知识库模式，使用translate接口
    handleTranslateMessage(messageContent)
  } else {
    // 有知识库模式，使用原有的模拟回复逻辑
    handleKnowledgeBasedMessage(messageContent)
  }
}

// 处理无知识库聊天消息
function handleTranslateMessage(messageContent: string, isRegenerating: boolean = false, insertIndex: number = -1) {
  // 立即设置为正在处理状态，防止重复请求
  isTyping.value = true
  
  // 创建助手消息对象，先添加空内容，初始状态不显示
  const assistantMessage: Message = {
    type: 'assistant',
    content: '',
    time: getCurrentTime(),
    hasError: false,
    isStreaming: false // 初始状态为false，不显示回答框
  }
  
  // 如果是重新生成，直接添加到消息列表的末尾
  let assistantMessageAdded = false
  let messageIndex = -1
  
  if (isRegenerating) {
    // 重新生成时，将消息插入到指定的位置，而不是末尾
    if (insertIndex >= 0) {
      messages.value.splice(insertIndex, 0, assistantMessage)
      messageIndex = insertIndex
    } else {
      messages.value.push(assistantMessage)
      messageIndex = messages.value.length - 1
    }
    assistantMessageAdded = true
    isTyping.value = false
    assistantMessage.isStreaming = true
  }
  
  scrollToBottom()
  
  // 使用当前时间戳作为session_stamp
  const sessionStamp = Date.now().toString()
  
  try {
    // 如果已有连接，先关闭
    if (currentEventSource.value) {
      currentEventSource.value.close()
      currentEventSource.value = null
    }
    
    const eventSource = translateMessage(currentSessionTimestamp, messageContent, selectedModel.value)
    currentEventSource.value = eventSource
    
    // 处理delta事件（流式内容）
    eventSource.addEventListener("delta", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('Delta数据:', data)
        
        if (data.content) {
          console.log('正在添加内容:', data.content)
          
          // 如果这是第一个内容，添加助手消息到列表并关闭加载动画
          if (!assistantMessageAdded) {
            console.log('收到第一个内容，关闭加载动画，显示回答框')
            isTyping.value = false
            assistantMessage.isStreaming = true
            messages.value.push(assistantMessage)
            messageIndex = messages.value.length - 1
            assistantMessageAdded = true
          }
          
          // 处理换行符，将 \n 转换为 <br/>
          const processedContent = data.content.replace(/\n/g, '<br/>')
          
          // 直接通过数组索引更新，确保Vue响应式更新
          messages.value[messageIndex].content += processedContent
          
          console.log('添加后总内容长度:', messages.value[messageIndex].content.length)
          
          // 强制触发响应式更新
          messages.value = [...messages.value]
          
          // 立即滚动
  scrollToBottom()
  
          // 确保DOM更新后再次滚动
          nextTick(() => {
            scrollToBottom()
          })
        }
      } catch (e) {
        console.error('解析delta数据失败:', e, event.data)
      }
    })
    
    // 处理start事件（开始标志）
    eventSource.addEventListener("start", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('Start数据:', data)
        
        if (data.message && data.message.includes("ai_chat_start")) {
          console.log('AI开始响应，但继续显示加载动画直到收到第一个内容')
          // 保持isTyping为true，继续显示加载动画
          // 只有在收到第一个delta事件时才关闭加载动画并显示回答框
        }
      } catch (e) {
        console.error('解析start数据失败:', e, event.data)
      }
    })
    
    // 处理end事件（结束标志）
    eventSource.addEventListener("end", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('End数据:', data)
        
        if (data.message && data.message.includes("ai_chat_end")) {
          console.log('AI响应完全结束，显示已完成思考')
          eventSource.close()
          currentEventSource.value = null

          // 结束流式状态，显示"已完成思考"
          if (assistantMessageAdded && messageIndex !== -1) {
            messages.value[messageIndex].isStreaming = false
            
            // 处理Mermaid图表（如果有的话）
            const messageContent = messages.value[messageIndex].content
            if (messageContent.includes('```mermaid')) {
              // 将<br/>转换回\n以便正确识别Mermaid代码块
              const normalizedContent = messageContent.replace(/<br\s*\/?>/gi, '\n')
              
              processMermaidCharts(normalizedContent).then(mermaidProcessed => {
                const finalResult = marked.parse(mermaidProcessed)
                const finalContent = typeof finalResult === 'string' ? finalResult : mermaidProcessed
                
                // 更新消息内容
                messages.value[messageIndex].content = finalContent
                
                // 更新缓存
                processedContentCache.value.set(normalizedContent, finalContent)
                
                // 强制响应式更新
                messages.value = [...messages.value]
              }).catch(error => {
                console.error('流式结束后Mermaid处理失败:', error)
              })
            }
            
            messages.value = [...messages.value] // 强制响应式更新
          }
          
          // 检查是否返回了chatId，如果有则更新路由
          if (data.chatId && !currentChatId.value) {
            currentChatId.value = data.chatId
            // 更新路由，但不重新加载页面
            router.push({ name: 'ChatWithId', params: { chatId: data.chatId } })
            console.log('收到chatId，更新路由:', data.chatId)
          }
        }
      } catch (e) {
        console.error('解析end数据失败:', e, event.data)
        // 即使解析失败也要结束流式状态
        eventSource.close()
        currentEventSource.value = null
        if (assistantMessageAdded && messageIndex !== -1) {
          messages.value[messageIndex].isStreaming = false
          
          // 处理Mermaid图表（如果有的话）
          const messageContent = messages.value[messageIndex].content
          if (messageContent.includes('```mermaid')) {
            // 将<br/>转换回\n以便正确识别Mermaid代码块
            const normalizedContent = messageContent.replace(/<br\s*\/?>/gi, '\n')
            
            processMermaidCharts(normalizedContent).then(mermaidProcessed => {
              const finalResult = marked.parse(mermaidProcessed)
              const finalContent = typeof finalResult === 'string' ? finalResult : mermaidProcessed
              
              // 更新消息内容
              messages.value[messageIndex].content = finalContent
              
              // 更新缓存
              processedContentCache.value.set(normalizedContent, finalContent)
              
              // 强制响应式更新
              messages.value = [...messages.value]
            }).catch(error => {
              console.error('异常结束后Mermaid处理失败:', error)
            })
          }
          
          messages.value = [...messages.value] // 强制响应式更新
        }
      }
    })
  
    
    eventSource.onopen = () => {
      console.log('SSE连接已建立')
    }

    // 处理连接错误
    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error)
      console.log('EventSource状态:', eventSource.readyState)
      
      // 立即关闭连接，避免自动重连
      eventSource.close()
      currentEventSource.value = null
      
      // 结束加载状态
      isTyping.value = false
      
      // 如果还没有添加助手消息，先添加一个错误消息
      if (!assistantMessageAdded) {
        assistantMessage.hasError = true
        assistantMessage.content = '连接中断，请重试。'
        assistantMessage.isStreaming = false
        messages.value.push(assistantMessage)
        assistantMessageAdded = true
      } else if (messageIndex !== -1) {
        // 标记已有消息为错误状态
        messages.value[messageIndex].hasError = true
        messages.value[messageIndex].isStreaming = false
        if (!messages.value[messageIndex].content.trim()) {
          messages.value[messageIndex].content = '连接中断，请重试。'
        }
      }
      
      // 强制响应式更新
      messages.value = [...messages.value]
      ElMessage.error('连接中断，请重试')
    }
  
  } catch (error) {
    console.error('创建SSE连接失败:', error)
    isTyping.value = false
    
    // 如果还没有添加助手消息，先添加一个错误消息
    if (!assistantMessageAdded) {
      assistantMessage.hasError = true
      assistantMessage.content = '思考发生异常，请重试。'
      messages.value.push(assistantMessage)
      assistantMessageAdded = true
    } else {
      // 标记为错误状态，显示红色思考异常
      messages.value[messageIndex].hasError = true
      messages.value[messageIndex].isStreaming = false
      messages.value[messageIndex].content = '思考发生异常，请重试。'
    }
    messages.value = [...messages.value] // 强制响应式更新
    ElMessage.error('连接失败，请重试')
  }
}
// 处理渗漏预控固化点的演示
function handleLeakagePreventionDemo() {
  // 立即设置为正在处理状态
  isTyping.value = true
  
  // 创建助手消息对象
  const assistantMessage: Message = {
    type: 'assistant',
    content: '',
    time: getCurrentTime(),
    hasError: false,
    isStreaming: true
  }
  
  // 添加到消息列表
  messages.value.push(assistantMessage)
  const messageIndex = messages.value.length - 1
  
  // 关闭加载动画
  isTyping.value = false
  
  // 预定义的渗漏预控措施内容
  const leakagePreventionContent = `# 建设工程渗漏标准化预控措施

## 一、屋面渗漏预控（12项预控点）

### 1.1 正面渗水
1. **优先采用刚性防水技术**，屋面防水等级应为Ⅱ级，最少达25mm，蓄水试验不少于24小时
2. **种植屋面构造层**应符合规范（保温、排水）
3. **平屋面坡度**≥2%，排水口处坡度≥5%，雨水斗不少于4个（GB 50666-2011 8.5.2条）
4. **防水层应连续、封闭严密**，甩茬部位、伸缩缝、出屋面管道根部等处应加强（GB 50207-2012 4.4.1条）
5. **防水施工完成后**，进行闭水试验（JGJ/T299-2013 12.1.1条）

### 1.2 倒面渗水
1. **屋面防水附加层**应高出屋面完成面300mm，女儿墙压顶加盖压条
2. **屋面找平层厚度**≥20mm，抗压强度≥C20
3. **找平层厚度50mm时**应分仓施工（一次性浇筑不宜过大）（GB 50207-2012 8.5.5条）

### 1.3 节点渗水
1. **伸缩缝、沉降缝、变形缝部位**应加设密封材料并做附加层（GB 50207-2012 8.5.5条）
2. **屋面女儿墙、檐口、出屋面管道**等收头部位应密封严密

### 1.4 雨篷渗水
1. **雨篷与外墙连接处**应设置止水构造，雨篷上表面应有排水坡度

---

## 二、地下室渗漏预控（11项预控点）

### 2.1 正面渗水
1. **防水混凝土**应采用抗渗等级≥S6，掺外加剂，裂缝宽度≤0.2mm（GB 50108-2008 4.0.4条）
2. **底板混凝土厚度**≥500mm，结构加强筋布置合理（GB 50204-2015 7.3.1条）
3. **底板后浇带施工时**应控制好浇筑时间，严格养护

### 2.2 倒面渗水
1. **底板后浇带宽度**≥1m，防水附加层连续设置
2. **底板钢筋绑扎牢固**，施工缝应清理干净并加防水附加层

### 2.3 节点渗水
1. **穿墙螺杆**采用止水螺杆，且应设止水环
2. **穿墙管道**应采用刚性防水套管

### 2.4 顶板渗水
1. **顶板厚度**≥300mm，采用抗渗等级≥S6的混凝土
2. **顶板施工缝**应严格清理并加设止水钢板

### 2.5 墙体渗水
1. **墙体厚度**≥300mm，混凝土抗渗等级≥S6
2. **外墙应采用**刚性防水与柔性防水复合做法

---

## 三、多水房间渗漏预控（5项预控点）

### 3.1 正面渗水
1. **楼板厚度**≥120mm，坡向排水口，坡度≥2%
2. **楼板上部设置**刚性防水保护层，厚度≥25mm

### 3.2 节点渗水
1. **卫生间管道穿楼板处**，应做套管并用密封材料填塞
2. **阴阳角**应做附加防水层
3. **地漏应采用**防臭地漏，并与防水层紧密结合

---

## 四、管道渗水预控（10项预控点）

### 4.1 管道（给排水）本体渗漏
1. **严格按设计及规范**选用合格管材、阀门、接口、胶粘剂
2. **管道试压、通水试验**应符合规范要求
3. **严禁使用**不合格的接口、管件

### 4.2 设备接口渗水
1. **设备连接处**应加设密封圈或法兰垫片
2. **阀门接口**应进行严密性试验

### 4.3 甩口渗水
1. **管道预留甩口**应封堵严密
2. **二次装修时**，应使用合格管材并重新试压

### 4.4 管井渗水
1. **管井底部**应设置排水设施
2. **管井墙面**应抹灰密实，防止渗漏

### 4.5 管根渗水
1. **穿楼板、墙体的管根**应做刚性防水套管，并与结构结合紧密

---

## 五、外墙渗漏预控（12项预控点）

### 5.1 正面渗水
1. **外墙砌体**应分层错缝，砂浆饱满度≥90%
2. **外墙抹灰**应分层压实，厚度控制合理
3. **外墙防水涂料厚度**≥2mm，分两遍以上施工

### 5.2 外窗渗水
1. **外窗应采用**合格产品，窗框与墙体缝隙应填塞饱满
2. **窗台应有**排水坡度≥5%
3. **窗边应设置**防水附加层

### 5.3 节点渗水
1. **阳台女儿墙压顶**应做滴水线
2. **外墙伸缩缝**应填嵌密封材料

### 5.4 雨篷渗水
1. **雨篷压顶**应做滴水线
2. **雨篷与墙体连接处**应加设防水构造

### 5.5 幕墙渗水
1. **幕墙玻璃与框架结合处**应密封严密
2. **幕墙排水系统**应保持畅通

---

## 总结

**总计：50项预控点**
- 屋面渗漏预控：12项
- 地下室渗漏预控：11项  
- 多水房间渗漏预控：5项
- 管道渗水预控：10项
- 外墙渗漏预控：12项

---

*注：以上内容可进一步制作成Word文档或Excel表格（带分级编号），便于直接用于汇报或标准化手册。*`

  // 模拟流式输出效果
  let currentIndex = 0
  const content = leakagePreventionContent
  const interval = setInterval(() => {
    if (currentIndex < content.length) {
      const chunk = content.slice(currentIndex, currentIndex + 3) // 每次输出3个字符
      messages.value[messageIndex].content += chunk
      currentIndex += 3
      scrollToBottom()
    } else {
      clearInterval(interval)
      // 处理完成后，标记流式输出结束
      messages.value[messageIndex].isStreaming = false
    }
  }, 50) // 每50ms输出一次，模拟打字效果
}

// 处理有知识库的消息（使用真实API）
function handleKnowledgeBasedMessage(messageContent: string, isRegenerating: boolean = false, insertIndex: number = -1) {
  // 检查是否是渗漏预控固化点的特殊查询
  if (messageContent.trim() === '渗漏预控固化点预控措施') {
    handleLeakagePreventionDemo()
    return
  }
  
  // 立即设置为正在处理状态，防止重复请求
  isTyping.value = true
  
  // 创建助手消息对象，立即显示
  const assistantMessage: Message = {
    type: 'assistant',
    content: '',
    time: getCurrentTime(),
    hasError: false,
    isStreaming: true // 初始状态为true，立即显示回答框
  }
  
  // 如果是重新生成，直接添加到消息列表的末尾
  let assistantMessageAdded = false
  let messageIndex = -1
  
  if (isRegenerating) {
    // 重新生成时，将消息插入到指定的位置，而不是末尾
    if (insertIndex >= 0) {
      messages.value.splice(insertIndex, 0, assistantMessage)
      messageIndex = insertIndex
    } else {
      messages.value.push(assistantMessage)
      messageIndex = messages.value.length - 1
    }
    assistantMessageAdded = true
    isTyping.value = false
    assistantMessage.isStreaming = true
  }
  
  scrollToBottom()
  
  // 使用当前时间戳作为session_stamp
  const sessionStamp = Date.now().toString()
  
  // 准备知识库数据
  const knowledgeData = {
    enterpriseKnowledge: getEnterpriseKnowledgeDetails().length > 0 ? getEnterpriseKnowledgeDetails() : undefined,
    personalKnowledge: getPersonalKnowledgeDetails().length > 0 ? getPersonalKnowledgeDetails() : undefined,
    searchSources: searchSources.value
  }
  
  try {
    // 如果已有连接，先关闭
    if (currentEventSource.value) {
      currentEventSource.value.close()
      currentEventSource.value = null
    }
    console.log('发送知识库聊天请求:', messageContent)
    const eventSource = knowledgeChatCompletion(currentSessionTimestamp, messageContent.trim(), knowledgeData, 'Doubao-seed-1-6-flash')
    currentEventSource.value = eventSource

    // 处理delta事件（流式内容）
    eventSource.addEventListener("delta", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('知识库聊天Delta数据:', data)
        
        if (data.content) {
          console.log('正在添加内容:', data.content)
          
          // 如果这是第一个内容，添加助手消息到列表并关闭加载动画
          if (!assistantMessageAdded) {
            console.log('收到第一个内容，关闭加载动画，显示回答框')
            isTyping.value = false
            assistantMessage.isStreaming = true
            messages.value.push(assistantMessage)
            messageIndex = messages.value.length - 1
            assistantMessageAdded = true
          }
          
          // 处理换行符，将 \n 转换为 <br/>
          const processedContent = data.content.replace(/\n/g, '<br/>')
          
          // 直接通过数组索引更新，确保Vue响应式更新
          messages.value[messageIndex].content += processedContent
          
          console.log('添加后总内容长度:', messages.value[messageIndex].content.length)
          
          // 强制触发响应式更新
          messages.value = [...messages.value]
          
          // 立即滚动
          scrollToBottom()
          
          // 确保DOM更新后再次滚动
          nextTick(() => {
            scrollToBottom()
          })
        }
      } catch (e) {
        console.error('解析delta数据失败:', e, event.data)
      }
    })
    
    // 处理start事件（开始标志）
    eventSource.addEventListener("start", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('知识库聊天Start数据:', data)
        
        if (data.message && data.message.includes("ai_chat_start")) {
          console.log('AI开始响应，但继续显示加载动画直到收到第一个内容')
          isTyping.value=false
          // 保持isTyping为true，继续显示加载动画
          // 只有在收到第一个delta事件时才关闭加载动画并显示回答框
        }
      } catch (e) {
        console.error('解析start数据失败:', e, event.data)
      }
    })
    
    // 处理end事件（结束标志）
    eventSource.addEventListener("end", (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('知识库聊天End数据:', data)
        
        if (data.message && data.message.includes("ai_chat_stop")) {
          console.log('AI响应完全结束，显示已完成思考')
          eventSource.close()
          currentEventSource.value = null

          // 结束流式状态，显示"已完成思考"
          if (assistantMessageAdded && messageIndex !== -1) {
            messages.value[messageIndex].isStreaming = false
            
            // 处理Mermaid图表（如果有的话）
            const messageContent = messages.value[messageIndex].content
            if (messageContent.includes('```mermaid')) {
              // 将<br/>转换回\n以便正确识别Mermaid代码块
              const normalizedContent = messageContent.replace(/<br\s*\/?>/gi, '\n')
              
              processMermaidCharts(normalizedContent).then(mermaidProcessed => {
                const finalResult = marked.parse(mermaidProcessed)
                const finalContent = typeof finalResult === 'string' ? finalResult : mermaidProcessed
                
                // 更新消息内容
                messages.value[messageIndex].content = finalContent
                
                // 更新缓存
                processedContentCache.value.set(normalizedContent, finalContent)
                
                // 强制响应式更新
                messages.value = [...messages.value]
              }).catch(error => {
                console.error('流式结束后Mermaid处理失败:', error)
              })
            }
            
            messages.value = [...messages.value] // 强制响应式更新
          }
          
          // 刷新侧边栏以更新近期对话
          try {
            refreshSidebarItems()
          } catch (error) {
            console.error('刷新侧边栏失败:', error)
          }
          
          // 检查是否返回了chatId，如果有则更新路由
          if (data.chatId && !currentChatId.value) {
            currentChatId.value = data.chatId
            // 更新路由，但不重新加载页面
            router.push({ name: 'ChatWithId', params: { chatId: data.chatId } })
            console.log('知识库聊天收到chatId，更新路由:', data.chatId)
          }
        }
      } catch (e) {
        console.error('解析end数据失败:', e, event.data)
        // 即使解析失败也要结束流式状态
        eventSource.close()
        currentEventSource.value = null
        if (assistantMessageAdded && messageIndex !== -1) {
          messages.value[messageIndex].isStreaming = false
          
          // 处理Mermaid图表（如果有的话）
          const messageContent = messages.value[messageIndex].content
          if (messageContent.includes('```mermaid')) {
            // 将<br/>转换回\n以便正确识别Mermaid代码块
            const normalizedContent = messageContent.replace(/<br\s*\/?>/gi, '\n')
            
            processMermaidCharts(normalizedContent).then(mermaidProcessed => {
              const finalResult = marked.parse(mermaidProcessed)
              const finalContent = typeof finalResult === 'string' ? finalResult : mermaidProcessed
              
              // 更新消息内容
              messages.value[messageIndex].content = finalContent
              
              // 更新缓存
              processedContentCache.value.set(normalizedContent, finalContent)
              
              // 强制响应式更新
              messages.value = [...messages.value]
            }).catch(error => {
              console.error('异常结束后Mermaid处理失败:', error)
            })
          }
          
          messages.value = [...messages.value] // 强制响应式更新
        }
      
      // 刷新侧边栏以更新近期对话
      try {
          refreshSidebarItems()
      } catch (error) {
        console.error('刷新侧边栏失败:', error)
      }
    }
    })
    
    // 处理错误
    eventSource.addEventListener("error", (event) => {
      console.error('知识库聊天EventSource错误:', event)
      eventSource.close()
      currentEventSource.value = null
      if (!assistantMessageAdded) {
        assistantMessage.hasError = true
        assistantMessage.content = '抱歉，知识库聊天出现错误，请稍后重试。'
        assistantMessage.isStreaming = false
        messages.value.push(assistantMessage)
        assistantMessageAdded = true
      }
      

      
      isTyping.value = false
    })
    
  } catch (error) {
    console.error('知识库聊天失败:', error)
    isTyping.value = false
    
    console.log(assistantMessageAdded)
    // 如果还没有添加助手消息，先添加一个错误消息
    if (!assistantMessageAdded) {
      assistantMessage.hasError = true
      assistantMessage.content = '思考发生异常，请重试。'
      messages.value.push(assistantMessage)
      assistantMessageAdded = true
    } else {
      // 标记为错误状态，显示红色思考异常
      messages.value[messageIndex].hasError = true
      messages.value[messageIndex].isStreaming = false
      messages.value[messageIndex].content = '思考发生异常，请重试。'
    }
    messages.value = [...messages.value] // 强制响应式更新
    ElMessage.error('连接失败，请重试')
  }
}

function toggleKnowledge(id: string) {
  // 根据当前选择的搜索来源，确定应该操作哪个知识库
  // 如果同时选择了企业和个人，需要判断这个id属于哪个知识库
  const isEnterpriseItem = enterpriseOptions.value.some(opt => opt.id === id)
  const isPersonalItem = personalOptions.value.some(opt => opt.id === id)

  if (isEnterpriseItem && searchSources.value.includes('enterprise')) {
    const index = selectedEnterpriseKnowledge.value.indexOf(id)
    if (index > -1) {
      selectedEnterpriseKnowledge.value.splice(index, 1)
    } else {
      selectedEnterpriseKnowledge.value.push(id)
    }
  } else if (isPersonalItem && searchSources.value.includes('personal')) {
    const index = selectedPersonalKnowledge.value.indexOf(id)
    if (index > -1) {
      selectedPersonalKnowledge.value.splice(index, 1)
    } else {
      selectedPersonalKnowledge.value.push(id)
    }
  }
}
/* 
function removeKnowledge(id: string) {
  if (searchSource.value === 'enterprise') {
    const index = selectedEnterpriseKnowledge.value.indexOf(id)
    if (index > -1) {
      selectedEnterpriseKnowledge.value.splice(index, 1)
    }
  } else if (searchSource.value === 'personal') {
    const index = selectedPersonalKnowledge.value.indexOf(id)
    if (index > -1) {
      selectedPersonalKnowledge.value.splice(index, 1)
    }
  }
}
 */
// 获取搜索来源卡片样式类
const getSourceCardClass = (category?: string) => {
  // if (!category) return ''

  // 企业知识库相关分类
/*   if (['企业标准', '技术规范', '质量管理', '安全标准', '技术标准', '施工指南', '安全管理'].includes(category)) {
    return 'enterprise-source'
  } */

  // 个人知识库相关分类
 /*  if (['个人笔记', '经验分享', '学习笔记', '管理心得'].includes(category)) {
    return 'personal-source'
  } */

  return 'enterprise-source'
}

// 获取搜索来源分类标签样式类
const getSourceCategoryClass = (category?: string) => {
  // if (!category) return ''

  // 企业知识库相关分类
  /* if (['企业标准', '技术规范', '质量管理', '安全标准', '技术标准', '施工指南', '安全管理'].includes(category)) {
    return 'enterprise-category'
  } */

  // 个人知识库相关分类
  /* if (['个人笔记', '经验分享', '学习笔记', '管理心得'].includes(category)) {
    return 'personal-category'
  } */

  return 'enterprise-category'
}

const textareaRef = ref<HTMLTextAreaElement>()

function adjustTextareaHeight() {
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto'
    textareaRef.value.style.height = textareaRef.value.scrollHeight + 'px'
  }
}

// 复制消息
const copyMessage = async (content: string) => {
  try {
    // 移除HTML标签，只复制纯文本
    const textContent = content.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ')
    await navigator.clipboard.writeText(textContent)
    ElMessage.success('复制成功')
  } catch (error) {
    // 如果clipboard API不可用，使用fallback方法
    try {
      const textArea = document.createElement('textarea')
      textArea.value = content.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ')
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      ElMessage.success('复制成功')
    } catch {
      ElMessage.error('复制失败，请手动选择文本复制')
    }
  }
}

// 下载消息
const downloadMessage = (content: string) => {
  try {
    // 移除HTML标签，保留纯文本格式
    const textContent = content
      .replace(/<br\s*\/?>/gi, '\n')
      .replace(/<\/p>/gi, '\n')
      .replace(/<p[^>]*>/gi, '')
      .replace(/<h[1-6][^>]*>/gi, '\n')
      .replace(/<\/h[1-6]>/gi, '\n')
      .replace(/<li[^>]*>/gi, '• ')
      .replace(/<\/li>/gi, '\n')
      .replace(/<[^>]*>/g, '')
      .replace(/&nbsp;/g, ' ')
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/\n\s*\n/g, '\n\n') // 清理多余的空行
      .trim()

    const blob = new Blob([textContent], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `智能问答_${new Date().toLocaleString().replace(/[/:]/g, '-')}.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 切换翻译状态
const toggleTranslation = (message: Message) => {
  if (message.isTranslated) {
    // 返回原文
    if (message.originalContent) {
      message.content = message.originalContent
      message.isTranslated = false
      ElMessage.success('已返回原文')
    }
  } else {
    // 翻译内容
    ElMessage.info('正在翻译...')

    setTimeout(() => {
      // 保存原文
      message.originalContent = message.content

      // 翻译内容
      const translatedContent = translateContent(message.content)
      message.content = translatedContent
      message.isTranslated = true

      ElMessage.success('翻译完成')
    }, 1500)
  }
}

// 翻译内容函数
const translateContent = (content: string): string => {
  // 这里可以集成真实的翻译API，比如百度翻译、谷歌翻译等
  // 现在提供更完整的模拟翻译

  const translations: { [key: string]: string } = {
    // 标题翻译
    '管道施工基本流程': 'Basic Pipeline Construction Process',
    '施工准备阶段': 'Construction Preparation Phase',
    '施工实施阶段': 'Construction Implementation Phase',
    '验收阶段': 'Acceptance Phase',
    '焊接工艺标准要求': 'Welding Process Standard Requirements',
    '焊接前准备': 'Pre-welding Preparation',
    '焊接过程控制': 'Welding Process Control',
    '安全防护措施': 'Safety Protection Measures',
    '质量控制要点': 'Quality Control Points',

    // 内容翻译
    '图纸审查': 'Drawing Review',
    '详细审查施工图纸和技术规范': 'Detailed review of construction drawings and technical specifications',
    '材料检验': 'Material Inspection',
    '检查材料质量证明文件': 'Check material quality certification documents',
    '现场确认': 'Site Confirmation',
    '确认施工现场条件和安全措施': 'Confirm construction site conditions and safety measures',
    '管道预制和组装': 'Pipeline Prefabrication and Assembly',
    '管道安装和连接': 'Pipeline Installation and Connection',
    '焊接作业': 'Welding Operations',
    '执行焊接工艺规程': 'Execute welding process procedures',
    '质量检验和测试': 'Quality Inspection and Testing',
    '压力试验': 'Pressure Test',
    '防腐检查': 'Anti-corrosion Inspection',
    '竣工验收': 'Completion Acceptance',
    '重要提醒': 'Important Reminder',
    '严格按照验收标准执行': 'Strictly follow acceptance standards',
    '安全第一': 'Safety First',
    '施工过程中请严格遵守安全操作规程': 'Please strictly follow safety operating procedures during construction',

    // 通用词汇
    '您好': 'Hello',
    '智能助手': 'Intelligent Assistant',
    '我可以帮助您': 'I can help you',
    '技术问题解答': 'Technical Problem Solving',
    '提示': 'Tips'
  }

  let translatedContent = content

  // 按照长度排序，优先匹配长的短语
  const sortedTranslations = Object.entries(translations).sort((a, b) => b[0].length - a[0].length)

  sortedTranslations.forEach(([chinese, english]) => {
    const regex = new RegExp(chinese, 'g')
    translatedContent = translatedContent.replace(regex, english)
  })

  // 如果内容基本没有变化，说明没有匹配的翻译
  const originalText = content.replace(/<[^>]*>/g, '').trim()
  const translatedText = translatedContent.replace(/<[^>]*>/g, '').trim()

  if (originalText === translatedText && originalText.length > 0) {
    // 返回一个通用的英文翻译提示
    return content.replace(originalText, 'English Translation: This content requires professional translation service integration.')
  }

  return translatedContent
}

// 删除消息
const deleteMessage = (message: Message) => {
  const index = messages.value.findIndex(msg => msg.time === message.time)
  if (index > -1) {
    messages.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 扩写消息
const expandMessage = (message: Message) => {
  ElMessage.info('正在扩写内容...')

  setTimeout(() => {
    const expandedContent = expandContent(message.content)
    
    // 直接在当前消息中添加扩写内容
    message.expandedContent = expandedContent
    
    // 强制响应式更新
    messages.value = [...messages.value]
    
    scrollToBottom()
    ElMessage.success('扩写完成')
  }, 2000)
}

// 扩写内容函数
const expandContent = (originalContent: string): string => {
  const textContent = originalContent.replace(/<[^>]*>/g, '').trim()

  if (textContent.includes('管道施工')) {
    return `# 📋 管道施工详细作业指导

## 前期准备阶段

### 🔍 技术准备
- **图纸会审**：组织设计、施工、监理等各方进行图纸会审
- **技术交底**：对施工班组进行详细的技术交底
- **方案编制**：编制专项施工方案和安全技术措施

### 📦 材料准备
- **材料验收**：严格按照标准验收管材、管件等材料
- **质量证明**：核查材质证明书、检验报告等文件
- **存储管理**：按要求分类存放，防止损坏和混用

## 施工实施阶段

### 🔧 管道预制
1. **精确下料**：根据施工图纸和现场实测尺寸进行下料
2. **坡口加工**：确保坡口角度、钝边符合焊接要求
3. **预制组对**：严格控制管道轴线和组对间隙
4. **预制焊接**：按照焊接工艺规程进行焊接作业

### 🏗️ 现场安装
1. **基础验收**：确认管道支撑基础符合设计要求
2. **管道就位**：使用合适的起重设备进行管道安装
3. **现场焊接**：严格控制焊接质量，做好层间清理
4. **质量检验**：进行外观检查和无损检测

## 质量控制要点

### ⚡ 焊接质量管理
- **焊工管理**：确保焊工持证上岗，技能符合要求
- **工艺控制**：严格按照焊接工艺规程执行
- **检验标准**：按照相关标准进行质量检验

### 🛡️ 安全防护措施
- **安全教育**：定期进行安全教育和技术培训
- **防护设备**：配备完善的安全防护用品
- **现场管理**：建立完善的现场安全管理制度

这份详细指导涵盖了管道施工的全过程，为确保工程质量提供了全面的技术支持。`
  }

  return `**【详细扩写版本】**

${textContent}

---

## 🔍 深度解析

### 技术背景
上述内容基于行业最佳实践和技术标准制定，结合了多年的工程经验和技术积累。

### 实施要点
1. **标准化操作**：建立标准化的作业程序和质量控制体系
2. **过程监控**：对关键工序进行全过程质量监控
3. **持续改进**：根据实施效果不断优化工艺流程

### 注意事项
- 严格遵守相关技术规范和安全标准
- 加强与各参建单位的沟通协调
- 做好施工记录和质量档案管理

### 预期效果
通过严格执行上述要求，可以确保工程质量达到设计标准，为后续运行维护奠定良好基础。`
}

// 简写消息
const summarizeMessage = (message: Message) => {
  ElMessage.info('正在简写内容...')

  setTimeout(() => {
    const summarizedContent = summarizeContent(message.content)
    
    // 直接在当前消息中添加简写内容
    message.summarizedContent = summarizedContent
    
    // 强制响应式更新
    messages.value = [...messages.value]
    
    scrollToBottom()
    ElMessage.success('简写完成')
  }, 1500)
}

// 简写内容函数
const summarizeContent = (originalContent: string): string => {
  const textContent = originalContent.replace(/<[^>]*>/g, '').trim()

  if (textContent.includes('管道施工')) {
    return `**📋 管道施工要点总结**

**准备阶段：**
- 图纸审查、技术交底
- 材料验收、设备检查

**施工阶段：**
- 管道预制、现场安装
- 焊接作业、质量检验

**控制要点：**
- 焊接质量、安装精度
- 安全防护、环境保护

**验收标准：**
- 压力试验、防腐检查
- 竣工验收、资料整理

💡 **核心提醒**：严格按规范施工，确保质量安全。`
  } else if (textContent.includes('管道维修')) {
    return `**🔧 管道维修核心要点**

**故障诊断：** 泄漏、腐蚀、损伤、松动
**维修方案：** 临时修复、永久修复
**作业流程：** 安全隔离→评估→维修→验收
**安全要求：** 介质排空、防护措施

⚠️ **关键提醒**：维修前确保安全，按规范操作。`
  } else if (textContent.includes('焊接施工')) {
    return `**⚡ 焊接施工安全要点**

**准备工作：** 环境检查、设备检查、人员资质
**过程控制：** 工艺参数、质量控制
**安全防护：** 防触电、防火防爆、防护用品
**应急处理：** 制定预案、及时响应

🚨 **安全第一**：严格防护，规范操作。`
  }

  // 通用简写逻辑
  const sentences = textContent.split(/[。！？.!?]/).filter(s => s.trim().length > 0)
  const keyPoints = sentences.slice(0, 3).map(s => s.trim()).join('；')

  return `**【简写版本】**

${keyPoints}

---

**核心要点：** 以上内容的关键信息已提炼，如需详细信息请参考完整版本。`
}

// 重新生成消息
const regenerateMessage = async (message: Message) => {
  if (isTyping.value) {
    ElMessage.warning('请等待当前回答完成后再重新生成')
    return
  }

  // 找到当前助手消息的索引
  // 使用更可靠的方式来查找消息：通过消息对象本身来查找
  const assistantMessageIndex = messages.value.findIndex(msg => msg === message)
  if (assistantMessageIndex === -1) {
    ElMessage.error('未找到对应的助手消息')
    return
  }
  
  console.log('=== 消息索引查找调试 ===')
  console.log('要重新生成的消息:', message.content.substring(0, 30))
  console.log('找到的索引:', assistantMessageIndex)
  console.log('该索引的消息:', messages.value[assistantMessageIndex]?.content.substring(0, 30))
  console.log('=== 消息索引查找调试结束 ===')

  // 查找对应的用户消息：每个AI回答对应它前面的第一个用户消息
  let userMessage: Message | null = null
  let userMessageIndex = -1
  
  // 从助手消息向前查找，找到对应的用户消息
  // 规则：每个AI回答对应它前面的第一个用户消息，这是固定的配对关系
  console.log('=== 开始查找用户消息 ===')
  console.log('当前助手消息索引:', assistantMessageIndex)
  
  for (let i = assistantMessageIndex - 1; i >= 0; i--) {
    console.log(`检查索引 ${i}:`, messages.value[i].type, messages.value[i].content.substring(0, 20))
    
    if (messages.value[i].type === 'user') {
      console.log(`找到用户消息，索引: ${i}, 内容: ${messages.value[i].content}`)
      userMessage = messages.value[i]
      userMessageIndex = i
      break
    }
  }
  
  console.log('最终选择的用户消息索引:', userMessageIndex)
  console.log('最终选择的用户消息内容:', userMessage?.content)
  console.log('=== 查找用户消息结束 ===')

  if (!userMessage) {
    ElMessage.error('未找到对应的用户消息')
    return
  }

  console.log('重新生成 - 用户消息:', userMessage.content)
  console.log('重新生成 - 助手消息索引:', assistantMessageIndex, '用户消息索引:', userMessageIndex)
  console.log('重新生成 - 当前消息列表长度:', messages.value.length)
  console.log('重新生成 - 消息列表内容:', messages.value.map(m => ({ type: m.type, content: m.content.substring(0, 20) })))
  
  // 调试：显示消息配对逻辑
  console.log('=== 消息配对调试信息 ===')
  for (let i = 0; i < messages.value.length; i++) {
    const msg = messages.value[i]
    console.log(`[${i}] ${msg.type}: ${msg.content.substring(0, 30)}...`)
  }
  console.log('当前助手消息索引:', assistantMessageIndex)
  console.log('找到的用户消息索引:', userMessageIndex)
  console.log('找到的用户消息内容:', userMessage.content)
  console.log('=== 配对逻辑结束 ===')
  
  // 构建重新发送的消息内容
  let messageContent = ''

  // 如果原消息包含文件，需要重新构建内容
  if (userMessage.files && userMessage.files.length > 0) {
    const fileUrls: string[] = []
    userMessage.files.forEach(file => {
      if (file.url) {
        fileUrls.push(file.url)
      }
    })

    if (!userMessage.content.trim() || userMessage.content === '发送了文件') {
      // 如果原来没有输入内容，只有文件
      messageContent = '请解析这个文件'
      if (fileUrls.length > 0) {
        messageContent += ' ' + fileUrls.join(' ')
      }
    } else {
      // 如果有输入内容和文件
      messageContent = userMessage.content
      if (fileUrls.length > 0) {
        messageContent += ' ' + fileUrls.join(' ')
      }
    }
  } else {
    // 没有文件，直接使用用户的输入内容
    messageContent = userMessage.content
  }

  console.log('重新生成，使用消息内容:', messageContent)

  // 使用原用户消息的知识库选择设置（只对用户消息有效）
  const originalSearchSources = (userMessage.type === 'user' && Array.isArray(userMessage.searchSources) && userMessage.searchSources.length > 0 && typeof userMessage.searchSources[0] === 'string') 
    ? userMessage.searchSources as string[] 
    : []
  const hasKnowledgeSelected = originalSearchSources.includes('personal') || originalSearchSources.includes('enterprise')
  
  // 临时保存当前的搜索源设置
  const currentSearchSources = [...searchSources.value]
  
  // 如果原消息有特定的知识库选择，临时应用它们
  if (originalSearchSources.length > 0) {
    searchSources.value = [...originalSearchSources]
  }
  
  // 先删除原来的助手消息
  messages.value.splice(assistantMessageIndex, 1)
  
  // 等待一下确保删除操作完成
  await nextTick()
  
  // 设置重新生成标志，防止重复添加消息
  const isRegenerating = ref(true)
  
  if (!hasKnowledgeSelected) {
    // 无知识库模式，使用translate接口重新生成
    // 传递重新生成标志和插入位置
    handleTranslateMessage(messageContent, true, assistantMessageIndex)
  } else {
    // 有知识库模式，使用原有的模拟回复逻辑
    // 重新设置知识库选择状态
    if (userMessage.enterpriseKnowledgeData) {
      // 恢复企业知识库选择
      selectedEnterpriseKnowledge.value = userMessage.enterpriseKnowledgeData.map(item => item.id)
    }
    if (userMessage.personalKnowledgeData) {
      // 恢复个人知识库选择
      selectedPersonalKnowledge.value = userMessage.personalKnowledgeData.map(item => item.id)
    }
    
    // 传递重新生成标志和插入位置
    handleKnowledgeBasedMessage(messageContent, true, assistantMessageIndex)
  }
  
  // 恢复原来的搜索源设置
  setTimeout(() => {
    searchSources.value = currentSearchSources
  }, 100)
}

// 生成替代内容
const generateAlternativeContent = (originalContent: string): string => {
  // 移除HTML标签获取纯文本
  const textContent = originalContent.replace(/<[^>]*>/g, '').trim()

  // 根据内容类型生成不同的替代版本
  if (textContent.includes('管道施工')) {
    return `# 管道施工作业指导

## 🔧 施工准备阶段
**材料准备**
- 管材质量检验与验收
- 焊接材料性能确认
- 施工工具设备检查

**技术准备**
- 施工图纸会审
- 技术交底完成
- 作业指导书编制

## 🏗️ 施工实施阶段
1. **管道预制**：按图纸要求进行管道预制加工
2. **现场安装**：严格按照安装工艺进行施工
3. **焊接作业**：执行焊接工艺规程，确保焊接质量
4. **质量检验**：进行外观检查和无损检测

## ✅ 验收阶段
- 压力试验
- 防腐检查
- 竣工验收

> 💡 **温馨提示**：施工过程中请严格遵守安全操作规程，确保人员安全。`
  } else if (textContent.includes('管道维修')) {
    return `# 管道维修技术指南

## 🔍 故障诊断
**常见问题类型**
- 管道泄漏
- 腐蚀损坏
- 机械损伤
- 接头松动

## 🛠️ 维修方案
**临时修复**
- 夹具修复法
- 胶粘修复法
- 套管修复法

**永久修复**
- 管段更换
- 补焊修复
- 重新连接

## 📋 维修流程
1. **安全隔离**：关闭相关阀门，确保作业安全
2. **损坏评估**：确定维修方案和所需材料
3. **维修实施**：按照技术规范进行维修作业
4. **质量验收**：进行压力测试和质量检查

⚠️ **安全提醒**：维修前必须确认管道内介质已排空，并做好安全防护。`
  } else if (textContent.includes('焊接施工')) {
    return `# 焊接施工安全作业规程

## 🔥 焊接前准备
**环境检查**
- 作业环境通风良好
- 清除易燃易爆物品
- 配备消防器材

**设备检查**
- 焊接设备完好
- 电缆绝缘良好
- 接地可靠

## 👷 人员要求
- 持证上岗
- 穿戴防护用品
- 身体状况良好

## ⚡ 焊接过程控制
**工艺参数**
- 焊接电流
- 电弧电压
- 焊接速度
- 层间温度

**质量控制**
- 焊缝外观检查
- 尺寸测量
- 无损检测

## 🛡️ 安全防护措施
- 防触电措施
- 防火防爆措施
- 有毒气体防护
- 弧光辐射防护

🚨 **紧急情况处理**：如发生意外，立即停止作业，采取应急措施并报告相关部门。`
  }

  // 默认重新生成
  return `**重新生成的内容：**

${textContent}

---

**补充说明：**
以上内容已根据最新的技术标准和安全规范进行了重新整理，提供了更加详细和实用的指导信息。如需了解更多具体细节，请随时提问。`
}

// 停止生成功能
const stopGeneration = () => {
  console.log('停止生成被调用')
  
  // 关闭SSE连接
  if (currentEventSource.value) {
    console.log('关闭SSE连接')
    currentEventSource.value.close()
    currentEventSource.value = null
  }
  
  // 停止打字效果
  if (currentTypingTimeout.value) {
    console.log('清除定时器')
    clearTimeout(currentTypingTimeout.value)
    currentTypingTimeout.value = null
  }
  
  // 强制设置为非输入状态
  isTyping.value = false
  console.log('设置isTyping为false')
  
  // 如果当前有正在流式生成的消息，标记为完成
  const lastMessage = messages.value[messages.value.length - 1]
  if (lastMessage && lastMessage.isStreaming) {
    console.log('标记消息为完成')
    lastMessage.isStreaming = false
  }
  
  ElMessage.info('已停止生成')
}

// 添加timeout引用
const currentTypingTimeout = ref<number | null>(null)

// 企业知识库分类数据
const enterpriseKnowledgeCategories = ref([
  {
    id: 'shiyi-library',
    name: '十一智库-资料',
    icon: '📚',
    children: [
      {
        id: 'external',
        name: '外部',
        children: [
          {
            id: 'regulations',
            name: '规范、图集',
            children: [
              {
                id: 'construction-standards',
                name: '施工规范、图集',
                children: [
                  {
                    id: 'construction-regulations',
                    name: '施工规范',
                    children: [
                      { id: 'national-construction', name: '国家规范' },
                      { id: 'industry-construction', name: '行业规范' },
                      { id: 'local-construction', name: '地方规范' }
                    ]
                  },
                  {
                    id: 'construction-atlas',
                    name: '施工图集',
                    children: [
                      { id: 'national-atlas', name: '国家规范' },
                      { id: 'industry-atlas', name: '行业规范' },
                      { id: 'local-atlas', name: '地方规范' }
                    ]
                  }
                ]
              },
              {
                id: 'design-standards',
                name: '设计规范、图集',
                children: [
                  { id: 'electrical', name: '电' },
                  { id: 'building', name: '建筑' },
                  { id: 'structure', name: '结构' },
                  { id: 'heating', name: '暖' },
                  { id: 'water', name: '水' }
                ]
              }
            ]
          }
        ]
      },
      {
        id: 'internal',
        name: '内部',
        children: [
          {
            id: 'shaanxi-construction-holding',
            name: '陕西建工控股集团有限公司',
            children: [
              { id: 'holding-regulations', name: '制度' },
              { id: 'holding-standards', name: '标准' },
              { id: 'holding-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-construction-group',
            name: '陕西建工集团股份有限公司',
            children: [
              { id: 'group-regulations', name: '制度' },
              { id: 'group-standards', name: '标准' },
              { id: 'group-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-11th-construction',
            name: '陕西建工第十一建设集团有限公司',
            children: [
              {
                id: 'enterprise-system-compilation',
                name: '企业制度汇编',
                children: [
                  { id: 'business-category', name: '经营类' },
                  { id: 'production-category', name: '生产类' },
                  { id: 'safety-category', name: '安全类' },
                  { id: 'technology-achievement', name: '科技成果类' },
                  { id: 'technical-quality', name: '技术质量类' },
                  { id: 'business-affairs', name: '商务类' },
                  { id: 'finance-category', name: '财务类' },
                  { id: 'hr-management', name: '人力资源与干部管理类' },
                  { id: 'administrative', name: '行政类' },
                  { id: 'party-discipline', name: '党风廉政建设与纪检监察类' },
                  { id: 'audit-category', name: '审计类' },
                  { id: 'worker-rights', name: '职工权益保障类' },
                  { id: 'design-category', name: '设计类' },
                  { id: 'comprehensive-management', name: '综合管理类' }
                ]
              },
              {
                id: 'enterprise-internal-control',
                name: '企业内部控制'
              },
              {
                id: 'standardization-manual',
                name: '标准化手册'
              },
              {
                id: 'process-standards-guide',
                name: '工艺标准指南'
              },
              {
                id: 'professional-knowledge',
                name: '专业知识',
                children: [
                  {
                    id: 'tech-achievements',
                    name: '科技成果',
                    children: [
                      { id: 'papers', name: '论文' },
                      { id: 'patents', name: '专利' },
                      { id: 'construction-methods', name: '工法' }
                    ]
                  },
                  {
                    id: 'excellent-cases',
                    name: '优秀案例',
                    children: [
                      { id: 'enterprise-culture-type', name: '企业文化类' },
                      { id: 'party-innovation-type', name: '党建创新类' }
                    ]
                  },
                  { id: 'case-review-results', name: '案例复盘成果' },
                  { id: 'international-building-standards', name: '国际建筑说明通用规范' }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
])

// 个人知识库分类数据
const personalKnowledgeCategories = ref([
  {
    id: 'shiyi-library',
    name: '十一智库-资料',
    icon: '📚',
    children: [
      {
        id: 'external',
        name: '外部',
        children: [
          {
            id: 'regulations',
            name: '规范、图集',
            children: [
              {
                id: 'construction-standards',
                name: '施工规范、图集',
                children: [
                  {
                    id: 'construction-regulations',
                    name: '施工规范',
                    children: [
                      { id: 'national-construction', name: '国家规范' },
                      { id: 'industry-construction', name: '行业规范' },
                      { id: 'local-construction', name: '地方规范' }
                    ]
                  },
                  {
                    id: 'construction-atlas',
                    name: '施工图集',
                    children: [
                      { id: 'national-atlas', name: '国家规范' },
                      { id: 'industry-atlas', name: '行业规范' },
                      { id: 'local-atlas', name: '地方规范' }
                    ]
                  }
                ]
              },
              {
                id: 'design-standards',
                name: '设计规范、图集',
                children: [
                  { id: 'electrical', name: '电' },
                  { id: 'building', name: '建筑' },
                  { id: 'structure', name: '结构' },
                  { id: 'heating', name: '暖' },
                  { id: 'water', name: '水' }
                ]
              }
            ]
          }
        ]
      },
      {
        id: 'internal',
        name: '内部',
        children: [
          {
            id: 'shaanxi-construction-holding',
            name: '陕西建工控股集团有限公司',
            children: [
              { id: 'holding-regulations', name: '制度' },
              { id: 'holding-standards', name: '标准' },
              { id: 'holding-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-construction-group',
            name: '陕西建工集团股份有限公司',
            children: [
              { id: 'group-regulations', name: '制度' },
              { id: 'group-standards', name: '标准' },
              { id: 'group-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-11th-construction',
            name: '陕西建工第十一建设集团有限公司',
            children: [
              {
                id: 'enterprise-system-compilation',
                name: '企业制度汇编',
                children: [
                  { id: 'business-category', name: '经营类' },
                  { id: 'production-category', name: '生产类' },
                  { id: 'safety-category', name: '安全类' },
                  { id: 'technology-achievement', name: '科技成果类' },
                  { id: 'technical-quality', name: '技术质量类' },
                  { id: 'business-affairs', name: '商务类' },
                  { id: 'finance-category', name: '财务类' },
                  { id: 'hr-management', name: '人力资源与干部管理类' },
                  { id: 'administrative', name: '行政类' },
                  { id: 'party-discipline', name: '党风廉政建设与纪检监察类' },
                  { id: 'audit-category', name: '审计类' },
                  { id: 'worker-rights', name: '职工权益保障类' },
                  { id: 'design-category', name: '设计类' },
                  { id: 'comprehensive-management', name: '综合管理类' }
                ]
              },
              {
                id: 'enterprise-internal-control',
                name: '企业内部控制'
              },
              {
                id: 'standardization-manual',
                name: '标准化手册'
              },
              {
                id: 'process-standards-guide',
                name: '工艺标准指南'
              },
              {
                id: 'professional-knowledge',
                name: '专业知识',
                children: [
                  {
                    id: 'tech-achievements',
                    name: '科技成果',
                    children: [
                      { id: 'papers', name: '论文' },
                      { id: 'patents', name: '专利' },
                      { id: 'construction-methods', name: '工法' }
                    ]
                  },
                  {
                    id: 'excellent-cases',
                    name: '优秀案例',
                    children: [
                      { id: 'enterprise-culture-type', name: '企业文化类' },
                      { id: 'party-innovation-type', name: '党建创新类' }
                    ]
                  },
                  { id: 'case-review-results', name: '案例复盘成果' },
                  { id: 'international-building-standards', name: '国际建筑说明通用规范' }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
])

// 根据搜索来源和当前Tab页动态获取知识库分类
const knowledgeCategories = computed(() => {
  let categories: any[] = []

  // 如果同时选择了企业和个人知识库，根据当前激活的Tab页显示
  if (searchSources.value.includes('enterprise') && searchSources.value.includes('personal')) {
    if (activeKnowledgeTab.value === 'enterprise') {
      categories = enterpriseKnowledgeCategories.value
    } else {
      categories = personalKnowledgeCategories.value
    }
  } else if (searchSources.value.includes('enterprise')) {
    categories = enterpriseKnowledgeCategories.value
  } else if (searchSources.value.includes('personal')) {
    categories = personalKnowledgeCategories.value
  }

  // 如果有搜索关键词，进行过滤
  if (searchKeyword.value.trim()) {
    return filterCategories(categories, searchKeyword.value.trim())
  }

  return categories
})

// 递归过滤分类函数
const filterCategories = (categories: any[], keyword: string): any[] => {
  const filtered: any[] = []

  for (const category of categories) {
    // 检查当前分类名称是否匹配
    const nameMatch = category.name.toLowerCase().includes(keyword.toLowerCase())

    // 递归检查子分类
    let filteredChildren: any[] = []
    if (category.children) {
      filteredChildren = filterCategories(category.children, keyword)
    }

    // 如果当前分类名称匹配或有匹配的子分类，则包含此分类
    if (nameMatch || filteredChildren.length > 0) {
      filtered.push({
        ...category,
        children: filteredChildren.length > 0 ? filteredChildren : category.children
      })
    }
  }

  return filtered
}

// 处理搜索
const handleSearch = () => {
  // 搜索功能已经通过计算属性knowledgeCategories实现
  // 当searchKeyword变化时，knowledgeCategories会自动重新计算
  console.log('搜索关键词:', searchKeyword.value)

  // 如果有搜索结果，自动展开所有匹配的分类
  if (searchKeyword.value.trim()) {
    expandSearchResults()
  }
}

// 展开搜索结果
const expandSearchResults = () => {
  const expandIds: string[] = []

  // 递归收集所有匹配的分类ID
  const collectExpandIds = (categories: any[]) => {
    for (const category of categories) {
      expandIds.push(category.id)
      if (category.children) {
        collectExpandIds(category.children)
      }
    }
  }

  collectExpandIds(knowledgeCategories.value)
  expandedCategories.value = [...new Set([...expandedCategories.value, ...expandIds])]
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  // 重置展开状态到初始状态
  initializeExpandedState()
}

// 递归获取所有叶子节点（可选择的项目）
const getAllLeafItems = (items: any[]): string[] => {
  const leafItems: string[] = []

  items.forEach(item => {
    if (item.children && item.children.length > 0) {
      // 如果有子项，递归获取子项的叶子节点
      leafItems.push(...getAllLeafItems(item.children))
    } else {
      // 如果没有子项，这就是叶子节点
      leafItems.push(item.id)
    }
  })

  return leafItems
}

// 计算所有可选项（所有叶子节点）
const allKnowledgeItems = computed(() => {
  const allItems: string[] = []

  knowledgeCategories.value.forEach(category => {
    if (category.children && category.children.length > 0) {
      allItems.push(...getAllLeafItems(category.children))
    }
  })

  return allItems
})

// 判断是否全选
const isAllSelected = computed(() => {
  return allKnowledgeItems.value.length > 0 && 
         allKnowledgeItems.value.every(id => selectedKnowledge.value.includes(id))
})

// 全选功能
const selectAll = () => {
  // 如果同时选择了企业和个人知识库，根据当前激活的Tab页操作
  if (searchSources.value.includes('enterprise') && searchSources.value.includes('personal')) {
    if (activeKnowledgeTab.value === 'enterprise') {
      selectedEnterpriseKnowledge.value = [...allKnowledgeItems.value]
    } else {
      selectedPersonalKnowledge.value = [...allKnowledgeItems.value]
    }
  } else if (searchSources.value.includes('enterprise')) {
    selectedEnterpriseKnowledge.value = [...allKnowledgeItems.value]
  } else if (searchSources.value.includes('personal')) {
    selectedPersonalKnowledge.value = [...allKnowledgeItems.value]
  }
}

// 清除选择
const clearSelection = () => {
  // 如果同时选择了企业和个人知识库，根据当前激活的Tab页操作
  if (searchSources.value.includes('enterprise') && searchSources.value.includes('personal')) {
    if (activeKnowledgeTab.value === 'enterprise') {
      selectedEnterpriseKnowledge.value = []
    } else {
      selectedPersonalKnowledge.value = []
    }
  } else if (searchSources.value.includes('enterprise')) {
    selectedEnterpriseKnowledge.value = []
  } else if (searchSources.value.includes('personal')) {
    selectedPersonalKnowledge.value = []
  }
}

// 切换全选状态
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    clearSelection()
  } else {
    selectAll()
  }
}

// 统一的展开状态管理
const expandedCategories = ref<string[]>([]) // 展开的分类
const expandedItems = ref<string[]>([]) // 统一管理所有展开的项目

// 初始化默认展开状态
const initializeExpandedState = () => {
  const expanded = []
  if (searchSources.value.includes('enterprise')) {
    // 企业知识库默认展开第一级
    expanded.push('shiyi-library')
  }
  if (searchSources.value.includes('personal')) {
    // 个人知识库默认展开第一级
    expanded.push('personal-learning', 'personal-work', 'personal-resources')
  }
  expandedCategories.value = expanded
}

// 获取所有展开的项目
const getAllExpandedItems = () => {
  return [...expandedCategories.value, ...expandedItems.value]
}

// 处理展开/收起
const handleToggleExpand = (itemId: string) => {
  const index = expandedItems.value.indexOf(itemId)
  if (index > -1) {
    expandedItems.value.splice(index, 1)
  } else {
    expandedItems.value.push(itemId)
  }
}

// 处理选择
const handleToggleSelection = (item: any) => {
  if (item.children && item.children.length > 0) {
    toggleParentSelection(item)
  } else {
    toggleKnowledge(item.id)
  }
}

// 切换一级分类展开状态
const toggleCategory = (categoryId: string) => {
  const index = expandedCategories.value.indexOf(categoryId)
  if (index > -1) {
    expandedCategories.value.splice(index, 1)
  } else {
    expandedCategories.value.push(categoryId)
  }
}

// 这些函数已被统一的 handleToggleExpand 替代

// 检查是否所有子项都被选中
const isAllChildrenSelected = (item: any): boolean => {
  if (!item.children || item.children.length === 0) return false
  return item.children.every((child: any) => {
    if (child.children && child.children.length > 0) {
      return isAllChildrenSelected(child)
    }
    return selectedKnowledge.value.includes(child.id)
  })
}

// 检查是否部分子项被选中
const isSomeChildrenSelected = (item: any): boolean => {
  if (!item.children || item.children.length === 0) return false
  return item.children.some((child: any) => {
    if (child.children && child.children.length > 0) {
      return isSomeChildrenSelected(child) || isAllChildrenSelected(child)
    }
    return selectedKnowledge.value.includes(child.id)
  })
}

// 获取某个父级项目下的所有叶子节点ID
const getChildrenLeafIds = (item: any): string[] => {
  if (!item.children || item.children.length === 0) {
    return [item.id]
  }

  const leafIds: string[] = []
  item.children.forEach((child: any) => {
    leafIds.push(...getChildrenLeafIds(child))
  })

  return leafIds
}

// 切换父级选择状态（选中/取消选中所有子项）
const toggleParentSelection = (item: any) => {
  const childrenIds = getChildrenLeafIds(item)
  const allSelected = isAllChildrenSelected(item)

  if (allSelected) {
    // 如果全部选中，则取消选中所有子项
    childrenIds.forEach(id => {
      const index = selectedKnowledge.value.indexOf(id)
      if (index > -1) {
        selectedKnowledge.value.splice(index, 1)
      }
    })
  } else {
    // 如果未全部选中，则选中所有子项
    childrenIds.forEach(id => {
      if (!selectedKnowledge.value.includes(id)) {
        selectedKnowledge.value.push(id)
      }
    })
  }
}

// 根据ID获取知识库分类名称的递归函数
const getKnowledgeCategoryName = (categories: any[], id: string): string | null => {
  for (const category of categories) {
    if (category.id === id) {
      return category.name
    }
    if (category.children && category.children.length > 0) {
      const found = getKnowledgeCategoryName(category.children, id)
      if (found) return found
    }
  }
  return null
}

// 获取企业知识库分类详细信息
const getEnterpriseKnowledgeDetails = (): Array<{id: string, name: string}> => {
  return selectedEnterpriseKnowledge.value.map(id => ({
    id,
    name: getKnowledgeCategoryName(enterpriseKnowledgeCategories.value, id) || id
  }))
}

// 获取个人知识库分类详细信息
const getPersonalKnowledgeDetails = (): Array<{id: string, name: string}> => {
  return selectedPersonalKnowledge.value.map(id => ({
    id,
    name: getKnowledgeCategoryName(personalKnowledgeCategories.value, id) || id
  }))
}

// 获取知识库分类数据的函数
const fetchKnowledgeCategories = async () => {
  try {
    // 这里替换为实际的API调用
    // const response = await api.getKnowledgeCategories()
    // knowledgeCategories.value = response.data

    // 目前使用mock数据
    console.log('使用Mock数据加载知识库分类')
  } catch (error) {
    console.error('获取知识库分类失败:', error)
    ElMessage.error('获取知识库分类失败')
  }
}

// 获取路由信息
const route = useRoute()
const router = useRouter()

// 当前会话的chatId，用于持久化聊天记录
const currentChatId = ref<string | null>(null)

// 从localStorage恢复聊天记录的函数
const loadChatHistory = () => {
  if (currentChatId.value) {
    console.log('开始加载聊天历史，chatId:', currentChatId.value)
    
    // 首先尝试从localStorage加载
    const savedData = localStorage.getItem(`chat_${currentChatId.value}`)
    if (savedData) {
      try {
        const data = JSON.parse(savedData)
        messages.value = data.messages || []
        currentSessionTimestamp = data.timestamp || new Date().getTime().toString()
        selectedModel.value = data.model || 'Deepseek-r1'
        
        // 恢复知识库选择状态
        if (data.searchSources) {
          searchSources.value = data.searchSources
        }
        if (data.enterpriseKnowledge) {
          selectedEnterpriseKnowledge.value = data.enterpriseKnowledge
        }
        if (data.personalKnowledge) {
          selectedPersonalKnowledge.value = data.personalKnowledge
        }
        
        console.log('从localStorage恢复聊天记录:', data)
        return
      } catch (e) {
        console.error('恢复聊天记录失败:', e)
      }
    }
    
    // 如果localStorage中没有，使用mock数据（模拟从近期对话跳转过来的情况）
    console.log('localStorage中没有找到记录，加载Mock数据')
    loadMockChatHistory(currentChatId.value)
  } else {
    // 如果没有chatId，显示默认欢迎消息
    console.log('没有chatId，显示默认欢迎消息')
    showDefaultWelcome()
  }
}
// 主题映射
const topicMap = {
  'pipeline-construction': '管道施工',
  'pipeline-maintenance': '管道维修',
  'welding-construction': '焊接施工注意'
}

// 防止重复处理主题的标志
const processedTopic = ref<string | null>(null)
// 获取主题相关的回复
const getTopicResponse = (topic: string): string => {
  switch (topic) {
    case 'pipeline-construction':
      return `<h1 class="message-heading message-h1">管道施工指南</h1>

<p>关于管道施工，我为您整理了以下要点：</p>

<h2 class="message-heading message-h2">1. 施工前准备</h2>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">图纸审查</strong>：详细审查施工图纸和技术规范</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">材料检验</strong>：检查材料质量证明文件</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">现场确认</strong>：确认施工现场条件和安全措施</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">人员配置</strong>：确保施工人员具备相应资质</span></div>

<h2 class="message-heading message-h2">2. 施工工艺流程</h2>
<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content">管道预制和组装</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content">管道安装和连接</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content">压力测试和质量检验</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content">防腐处理和保温</span></div>

<h2 class="message-heading message-h2">3. 质量控制要点</h2>
<blockquote class="message-quote"><strong class="message-bold">重要提醒</strong>：质量控制是管道施工的核心环节</blockquote>

<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">焊接质量控制</strong>：严格按照焊接工艺规程执行</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">防腐处理标准</strong>：确保防腐层厚度和附着力</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">安装精度要求</strong>：控制管道标高和坡度</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content"><strong class="message-bold">检测验收</strong>：进行无损检测和压力试验</span></div>

<h2 class="message-heading message-h2">4. 安全注意事项</h2>
<p>⚠️ <strong class="message-bold">安全第一，预防为主</strong></p>

<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">施工现场安全防护</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">特殊作业安全措施</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">应急预案制定</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">定期安全检查</span></div>

<hr class="message-divider">

<p>💡 <strong class="message-bold">提示</strong>：您还想了解哪个具体方面的详细信息？我可以为您提供更深入的技术指导。</p>`

    case 'pipeline-maintenance':
      return `<p>关于管道维修，我为您介绍以下内容：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">维修前检查</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">管道损坏程度评估</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">维修方案制定</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">安全隔离措施</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">常见维修方法</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">补焊修复</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">管段更换</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">套管修复</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">内衬修复</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">维修质量标准</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接质量要求</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">压力测试标准</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">防腐层修复</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">维修后验收</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">外观质量检查</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">压力试验</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">防腐层检测</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">运行测试</span></div>

<p>需要了解具体的维修技术或标准吗？</p>`

    case 'welding-construction':
      return `<p>关于焊接施工注意事项，请重点关注：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">焊前准备</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊工资质确认</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接材料检验</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接设备检查</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">环境条件评估</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">焊接工艺控制</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接参数设定</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接顺序安排</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">层间温度控制</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊后热处理</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">质量控制措施</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">焊接过程监控</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">外观质量检查</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">无损检测要求</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">返修处理程序</span></div>

<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">安全防护要求</strong></span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">个人防护用品</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">通风排烟措施</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">防火防爆措施</span></div>
<div class="message-list-item message-unordered-item"><span class="message-list-bullet">•</span><span class="message-list-content">有毒气体防护</span></div>

<p>您想深入了解哪个方面的焊接技术？</p>`

    default:
      return '<p>您好！我是智能助手，很高兴为您服务。请问有什么可以帮助您的吗？</p>'
  }
} 

// 加载Mock聊天历史数据
const loadMockChatHistory = (chatId: string) => {
  console.log('加载Mock聊天历史数据:', chatId)
  
  // 根据chatId生成对应的mock数据
  const mockData = generateMockChatData(chatId)
  
  if (mockData) {
    messages.value = mockData.messages
    currentSessionTimestamp = mockData.timestamp
    selectedModel.value = mockData.model
    
    // 根据mock数据设置知识库选择状态
    if (mockData.messages && mockData.messages.length > 0) {
      const firstMessage = mockData.messages[0]
      console.log('设置知识库选择状态，第一条消息:', firstMessage)
      
      // 设置搜索来源
      if (firstMessage.searchSources && Array.isArray(firstMessage.searchSources)) {
        // 确保搜索来源被正确设置
        const sources = firstMessage.searchSources.map(source => source)
        console.log('准备设置搜索来源:', sources)
        
        // 先清空，再设置新值，确保触发响应式更新
        searchSources.value = []
        console.log('搜索来源已清空')
        
        // 使用 nextTick 确保清空操作完成后再设置新值
        nextTick(() => {
          searchSources.value = sources
          console.log('搜索来源设置完成:', searchSources.value)
          
          // 再次使用 nextTick 确保值被正确设置
          nextTick(() => {
            console.log('最终搜索来源值:', searchSources.value)
            console.log('搜索来源数组长度:', searchSources.value.length)
            console.log('搜索来源是否包含enterprise:', searchSources.value.includes('enterprise'))
            console.log('搜索来源是否包含personal:', searchSources.value.includes('personal'))
          })
        })
      }
      
      // 安全地访问可能存在的属性并提取ID数组
      if ('enterpriseKnowledgeData' in firstMessage && firstMessage.enterpriseKnowledgeData) {
        const enterpriseData = firstMessage.enterpriseKnowledgeData as Array<{id: string, name: string}>
        selectedEnterpriseKnowledge.value = enterpriseData.map(item => item.id)
        console.log('设置企业知识库选择:', selectedEnterpriseKnowledge.value)
      }
      
      if ('personalKnowledgeData' in firstMessage && firstMessage.personalKnowledgeData) {
        const personalData = firstMessage.personalKnowledgeData as Array<{id: string, name: string}>
        selectedPersonalKnowledge.value = personalData.map(item => item.id)
        console.log('设置个人知识库选择:', selectedPersonalKnowledge.value)
      }
      
          // 强制更新UI
    nextTick(() => {
      console.log('知识库选择状态更新完成')
      console.log('当前搜索来源:', searchSources.value)
      console.log('当前企业知识库选择:', selectedEnterpriseKnowledge.value)
      console.log('当前个人知识库选择:', selectedPersonalKnowledge.value)
      
      // 延迟检查，确保值被正确设置
      setTimeout(() => {
        console.log('延迟检查 - 搜索来源:', searchSources.value)
        console.log('延迟检查 - 企业知识库选择:', selectedEnterpriseKnowledge.value)
        console.log('延迟检查 - 个人知识库选择:', selectedPersonalKnowledge.value)
        
        // 如果搜索来源还是空的，尝试重新设置
        if (searchSources.value.length === 0 && mockData.messages && mockData.messages.length > 0) {
          const firstMessage = mockData.messages[0]
          if (firstMessage.searchSources && Array.isArray(firstMessage.searchSources)) {
            console.log('重新设置搜索来源:', firstMessage.searchSources)
            searchSources.value = [...firstMessage.searchSources]
          }
        }
      }, 500)
    })
    }
    
    // 如果有主题信息，自动处理主题
    if (mockData.topic && !processedTopic.value) {
      processedTopic.value = mockData.topic
    }
    
    console.log('Mock聊天历史数据加载完成:', mockData)
  } else {
    // 如果没有找到对应的mock数据，显示默认欢迎消息
    showDefaultWelcome()
  }
}

// 生成Mock聊天数据
const generateMockChatData = (chatId: string) => {
  const mockChats = {
    'chat-001': {
      messages: [
        {
          type: 'user' as const,
          content: '我想了解管道施工的基本流程',
          time: getCurrentTime(),
          searchSources: ['enterprise'],
          enterpriseKnowledgeData: [{ id: 'pipeline-001', name: '管道施工规范' }]
        },
        {
          type: 'assistant' as const,
          content: getTopicResponse('pipeline-construction'),
          time: getCurrentTime(),
          searchSources: [
            {
              title: '管道施工规范',
              content: '管道施工的基本流程包括：施工准备、材料验收、管道预制、现场安装、焊接施工、质量检验等环节。本标准规定了管道施工的技术要求、质量控制要点和安全注意事项。',
              url: '/documents/pipeline-construction-standards'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'pipeline-001', name: '管道施工规范' }]
        },
        {
          type: 'user' as const,
          content: '焊接工艺有什么具体要求？',
          time: getCurrentTime(),
          searchSources: ['enterprise'],
          enterpriseKnowledgeData: [{ id: 'pipeline-001', name: '管道施工规范' }]
        },
        {
          type: 'assistant' as const,
          content: getTopicResponse('welding-construction'),
          time: getCurrentTime(),
          searchSources: [
            {
              title: '管道施工规范',
              content: '焊接工艺要求包括：焊接材料选择、工艺参数控制、预热温度管理、层间温度控制、质量检验等。本标准详细规定了管道焊接的技术要求和质量标准。',
              url: '/documents/pipeline-construction-standards'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'pipeline-001', name: '管道施工规范' }]
        }
      ],
      timestamp: new Date(Date.now() - 1000 * 60 * 30).getTime().toString(),
      model: 'Deepseek-r1',
      topic: 'pipeline-construction'
    },
    'chat-002': {
      messages: [
        {
          type: 'user' as const,
          content: '焊接工艺控制要点有哪些？',
          time: getCurrentTime(),
          searchSources: ['personal'],
          personalKnowledgeData: [{ id: 'welding-001', name: '焊接技术手册' }]
        },
        {
          type: 'assistant' as const,
          content: getTopicResponse('welding-construction'),
          time: getCurrentTime(),
          searchSources: [
            {
              title: '焊接技术手册',
              content: '焊接工艺控制要点包括：焊接材料选择、工艺参数控制、层间温度管理、质量检验等。本手册详细介绍了各种焊接方法的操作要点和质量标准。',
              url: '/documents/welding-technique-manual'
            }
          ],
          personalKnowledgeData: [{ id: 'welding-001', name: '焊接技术手册' }]
        },
        {
          type: 'user' as const,
          content: '层间温度控制有什么标准？',
          time: getCurrentTime(),
          searchSources: ['personal'],
          personalKnowledgeData: [{ id: 'welding-001', name: '焊接技术手册' }]
        },
        {
          type: 'assistant' as const,
          content: `<p>关于层间温度控制，有以下标准要求：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">预热温度</strong>：根据材料类型确定，一般碳钢为100-200℃，合金钢为200-300℃</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">层间温度</strong>：通常不超过预热温度+100℃，避免过热</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">温度测量</strong>：使用红外测温仪或接触式温度计</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">控制方法</strong>：通过焊接速度、电流大小、层间间隔时间调节</span></div>

<p>需要了解具体的温度控制参数吗？</p>`,
          time: getCurrentTime(),
          searchSources: [
            {
              title: '焊接技术手册',
              content: '层间温度控制是焊接工艺的关键参数，包括预热温度设定、层间温度控制、温度测量方法和控制手段等。本手册详细规定了各种材料的温度控制标准。',
              url: '/documents/welding-technique-manual'
            }
          ],
          personalKnowledgeData: [{ id: 'welding-001', name: '焊接技术手册' }]
        }
      ],
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2).getTime().toString(),
      model: 'Deepseek-r1',
      topic: 'welding-construction'
    },
    'chat-003': {
      messages: [
        {
          type: 'user' as const,
          content: '管道维修的关键步骤是什么？',
          time: getCurrentTime(),
          searchSources: ['enterprise', 'personal'],
          enterpriseKnowledgeData: [{ id: 'maintenance-001', name: '维修操作规程' }],
          personalKnowledgeData: [{ id: 'maintenance-002', name: '故障诊断手册' }]
        },
        {
          type: 'assistant' as const,
          content: getTopicResponse('pipeline-maintenance'),
          time: getCurrentTime(),
          searchSources: [
            {
              title: '维修操作规程',
              content: '管道维修的关键步骤包括：故障诊断、维修方案制定、安全措施准备、维修作业执行、质量验收等。本规程详细规定了各类维修作业的标准流程。',
              url: '/documents/maintenance-operation-procedures'
            },
            {
              title: '故障诊断手册',
              content: '故障诊断是维修工作的第一步，需要准确识别故障类型、分析故障原因、评估故障影响范围，为制定维修方案提供依据。',
              url: '/documents/fault-diagnosis-manual'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'maintenance-001', name: '维修操作规程' }],
          personalKnowledgeData: [{ id: 'maintenance-002', name: '故障诊断手册' }]
        },
        {
          type: 'user' as const,
          content: '补焊修复需要注意什么？',
          time: getCurrentTime(),
          searchSources: ['enterprise', 'personal'],
          enterpriseKnowledgeData: [{ id: 'maintenance-001', name: '维修操作规程' }],
          personalKnowledgeData: [{ id: 'maintenance-002', name: '故障诊断手册' }]
        },
        {
          type: 'assistant' as const,
          content: `<p>补焊修复需要注意以下关键点：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">缺陷清理</strong>：彻底清除裂纹、气孔等缺陷，确保清洁</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">坡口准备</strong>：开制合适的坡口角度和尺寸</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">焊接材料</strong>：选择与母材匹配的焊条或焊丝</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">工艺参数</strong>：严格控制电流、电压、焊接速度</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">5.</span><span class="message-list-content"><strong class="message-bold">质量检验</strong>：进行外观检查和无损检测</span></div>

<p>您想了解哪个具体环节的详细要求？</p>`,
          time: getCurrentTime(),
          searchSources: [
            {
              title: '维修操作规程',
              content: '补焊修复是管道维修的重要工艺，需要严格按照操作规程执行。包括缺陷清理、坡口准备、焊接材料选择、工艺参数控制、质量检验等关键环节。',
              url: '/documents/maintenance-operation-procedures'
            },
            {
              title: '故障诊断手册',
              content: '补焊修复前需要进行详细的故障诊断，确定缺陷类型、位置和程度，为制定修复方案提供准确的技术依据。',
              url: '/documents/fault-diagnosis-manual'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'maintenance-001', name: '维修操作规程' }],
          personalKnowledgeData: [{ id: 'maintenance-002', name: '故障诊断手册' }]
        }
      ],
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24).getTime().toString(),
      model: 'Deepseek-r1',
      topic: 'pipeline-maintenance'
    },
    'chat-004': {
      messages: [
        {
          type: 'user' as const,
          content: '施工现场安全管理有哪些要求？',
          time: getCurrentTime(),
          searchSources: ['enterprise'],
          enterpriseKnowledgeData: [{ id: 'safety-001', name: '安全管理制度' }]
        },
        {
          type: 'assistant' as const,
          content: `<p>施工现场安全管理要求包括：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">个人防护</strong>：必须佩戴安全帽、安全鞋、工作服等防护用品</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">安全标识</strong>：设置明显的安全警示标志和指示牌</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">作业许可</strong>：特殊作业需要办理作业许可证</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">应急预案</strong>：制定完善的应急救援预案</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">5.</span><span class="message-list-content"><strong class="message-bold">培训教育</strong>：定期进行安全培训和考核</span></div>

<p>需要了解具体的安全操作规程吗？</p>`,
          time: getCurrentTime(),
          searchSources: [
            {
              title: '安全管理制度',
              content: '施工现场安全管理要求包括个人防护、安全标识、作业许可、应急预案、培训教育等方面。本制度规定了各类施工活动的安全管理标准和操作规程。',
              url: '/documents/safety-management-system'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'safety-001', name: '安全管理制度' }]
        }
      ],
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24 * 2).getTime().toString(),
      model: 'Deepseek-r1',
      topic: 'safety-standards'
    },
    'chat-005': {
      messages: [
        {
          type: 'user' as const,
          content: '工程质量控制的关键环节有哪些？',
          time: getCurrentTime(),
          searchSources: ['enterprise'],
          enterpriseKnowledgeData: [{ id: 'quality-001', name: '质量控制标准' }]
        },
        {
          type: 'assistant' as const,
          content: `<p>工程质量控制的关键环节包括：</p>

<div class="message-list-item message-ordered-item"><span class="message-list-number">1.</span><span class="message-list-content"><strong class="message-bold">材料检验</strong>：严格检查材料质量证明文件和外观质量</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">2.</span><span class="message-list-content"><strong class="message-bold">施工工艺</strong>：按照标准工艺规程执行，控制关键参数</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">3.</span><span class="message-list-content"><strong class="message-bold">过程监控</strong>：实时监控施工过程，及时发现问题</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">4.</span><span class="message-list-content"><strong class="message-bold">验收标准</strong>：严格执行验收标准，确保质量达标</span></div>
<div class="message-list-item message-ordered-item"><span class="message-list-number">5.</span><span class="message-list-content"><strong class="message-bold">记录管理</strong>：建立完整的质量记录档案</span></div>

<p>您想了解哪个环节的具体要求？</p>`,
          time: getCurrentTime(),
          searchSources: [
            {
              title: '质量控制标准',
              content: '工程质量控制的关键环节包括材料检验、施工工艺、过程监控、验收标准、记录管理等。本标准详细规定了各环节的质量控制要求和验收标准。',
              url: '/documents/quality-control-standards'
            }
          ],
          enterpriseKnowledgeData: [{ id: 'quality-001', name: '质量控制标准' }]
        }
      ],
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3).getTime().toString(),
      model: 'Deepseek-r1',
      topic: 'quality-control'
    }
  }
  
  return mockChats[chatId as keyof typeof mockChats]
}

// 显示默认欢迎消息
const showDefaultWelcome = () => {
  // 清空现有消息
  messages.value = []
  
  // 设置默认模型
  selectedModel.value = 'Deepseek-r1'
  
  // 设置当前时间戳
  currentSessionTimestamp = new Date().getTime().toString()
  
  // 重置知识库选择状态
  searchSources.value = []
  selectedEnterpriseKnowledge.value = []
  selectedPersonalKnowledge.value = []
  
  console.log('显示默认欢迎消息')
}

// 模拟从近期对话跳转过来的情况（用于测试）
const simulateRecentChatNavigation = (chatId: string, topic?: string) => {
  console.log('模拟从近期对话跳转:', chatId, topic)
  
  // 设置chatId
  currentChatId.value = chatId
  
  // 设置主题
  if (topic && topicMap[topic as keyof typeof topicMap]) {
    processedTopic.value = topic
  }
  
  // 加载聊天历史
  loadChatHistory()
  
  // 更新URL，但不触发路由变化
  const newQuery: any = { ...route.query, chatId }
  if (topic) {
    newQuery.topic = topic
  }
  router.replace({ query: newQuery })
}

// 保存聊天记录到localStorage的函数
const saveChatHistory = () => {
  if (currentChatId.value) {
    const data = {
      messages: messages.value,
      timestamp: currentSessionTimestamp,
      model: selectedModel.value,
      searchSources: searchSources.value,
      enterpriseKnowledge: selectedEnterpriseKnowledge.value,
      personalKnowledge: selectedPersonalKnowledge.value
    }
    localStorage.setItem(`chat_${currentChatId.value}`, JSON.stringify(data))
    console.log('保存聊天记录到localStorage:', data)
  }
}

// 监听路由变化，处理chatId
watch(() => route.params.chatId, (newChatId) => {
  if (newChatId && typeof newChatId === 'string') {
    currentChatId.value = newChatId
    loadChatHistory()
  } else {
    currentChatId.value = null
  }
}, { immediate: true })

// 监听路由查询参数，处理从近期对话跳转过来的情况
watch(() => route.query, (newQuery) => {
  const chatId = Array.isArray(newQuery.chatId) ? newQuery.chatId[0] : newQuery.chatId as string
  const timestamp = Array.isArray(newQuery.timestamp) ? newQuery.timestamp[0] : newQuery.timestamp as string
  const topic = Array.isArray(newQuery.topic) ? newQuery.topic[0] : newQuery.topic as string
  
  if (chatId && chatId !== currentChatId.value) {
    console.log('检测到新的chatId，从近期对话跳转过来:', chatId)
    currentChatId.value = chatId
    
    // 如果有时间戳，使用传入的时间戳
    if (timestamp) {
      currentSessionTimestamp = timestamp
    }
    
    // 如果有主题参数，设置主题
    if (topic && topicMap[topic as keyof typeof topicMap]) {
      processedTopic.value = topic
    }
    
    // 加载聊天历史
    loadChatHistory()
  }
}, { immediate: true })

// 监听messages变化，自动保存
watch(messages, saveChatHistory, { deep: true })
watch(selectedModel, saveChatHistory)


// 处理URL参数中的主题
const handleTopicFromUrl = () => {
  const topic = route.query.topic as string

  // 如果已经处理过相同的主题，则不重复处理
  if (topic === processedTopic.value) {
    return
  }

  if (topic && topicMap[topic as keyof typeof topicMap]) {
    // 记录已处理的主题
    processedTopic.value = topic

    const topicName = topicMap[topic as keyof typeof topicMap]
    // 自动发送一个关于该主题的问题
    const welcomeMessage = `您好！我想了解关于${topicName}的相关信息，请为我介绍一下。`

    // 添加用户消息
    messages.value.push({
      type: 'user',
      content: welcomeMessage,
      time: getCurrentTime()
    })

    // 模拟AI回复
    setTimeout(() => {
      const aiResponse = getTopicResponse(topic)
      messages.value.push({
        type: 'assistant',
        content: aiResponse,
        time: getCurrentTime()
      })
      scrollToBottom()
    }, 1000)
  }
}







// 组件挂载时获取数据
onMounted(() => {
  fetchKnowledgeCategories()
  // 初始化展开状态
  initializeExpandedState()
  // 不在这里处理主题，因为watch已经设置了immediate: true
  
  // 初始化Mermaid
  mermaid.initialize({
    startOnLoad: true,
    theme: 'default',
    securityLevel: 'loose',
    themeVariables: {
      primaryColor: '#5b7cff',
      primaryTextColor: '#333',
      primaryBorderColor: '#5b7cff',
      lineColor: '#5b7cff',
      secondaryColor: '#f0f4ff',
      tertiaryColor: '#f8f9ff'
    }
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 关闭EventSource连接
  if (currentEventSource.value) {
    console.log('组件卸载，关闭EventSource连接')
    currentEventSource.value.close()
    currentEventSource.value = null
  }
})





// 获取当前用户头像文字
function getCurrentUserAvatar(): string {
  const currentUsername = localStorage.getItem('currentUsername')
  if (currentUsername) {
    return currentUsername.charAt(0).toUpperCase()
  }
  
  const userRole = localStorage.getItem('userRole') || 'user'
  switch (userRole) {
    case 'admin':
      return '管'
    case 'staff':
      return '员'
    default:
      return '用'
  }
}

// Markdown 渲染函数
const renderMarkdown = async (content: string): Promise<string> => {
  if (!content) return ''
  try {
    return await marked(content, {
      breaks: true,
      gfm: true
    })
  } catch (error) {
    console.error('Markdown 渲染错误:', error)
    return content
  }
}

// 处理Mermaid图表的函数
const processMermaidCharts = async (content: string): Promise<string> => {
  if (!content) return ''
  
  // 匹配Mermaid代码块的正则表达式  
  const mermaidRegex = /```mermaid\n([\s\S]*?)\n```/g
  let processedContent = content
  const mermaidBlocks: { original: string; id: string; code: string }[] = []
  
  // 找到所有Mermaid代码块
  let match
  let counter = 0
  while ((match = mermaidRegex.exec(content)) !== null) {
    const id = `mermaid-${Date.now()}-${counter++}`
    mermaidBlocks.push({
      original: match[0],
      id,
      code: match[1].trim()
    })
  }
  
  // 如果没有Mermaid代码块，直接返回原内容
  if (mermaidBlocks.length === 0) {
    return processedContent
  }
  
  // 渲染每个Mermaid图表
  for (const block of mermaidBlocks) {
    try {
      const { svg } = await mermaid.render(block.id, block.code)
      // 添加一个包装容器来改善样式
      const wrappedSvg = `<div class="mermaid-container" id="${block.id}-container">${svg}</div>`
      processedContent = processedContent.replace(block.original, wrappedSvg)
    } catch (error) {
      console.error('Mermaid渲染错误:', error)
      // 如果渲染失败，保留原始代码块
      const errorBlock = `<div class="mermaid-error">
        <p><strong>Mermaid图表渲染失败</strong></p>
        <pre><code>${block.code}</code></pre>
      </div>`
      processedContent = processedContent.replace(block.original, errorBlock)
    }
  }
  
  return processedContent
}

// 存储处理后的内容缓存
const processedContentCache = ref<Map<string, string>>(new Map())

// 合并连续的有序列表函数，并处理嵌套层级
const mergeConsecutiveOrderedLists = (html: string): string => {
  // 匹配连续的</ol><ol>模式并合并
  let processedHtml = html.replace(/<\/ol>\s*<ol>/g, '')
  
  // 处理嵌套的有序列表，确保子级使用正确的层级格式
  processedHtml = processedHtml.replace(
    /<ol[^>]*>([\s\S]*?)<\/ol>/g,
    (match, content) => {
      // 检查是否在另一个ol内部
      const parentMatch = match.match(/<ol[^>]*>[\s\S]*<ol[^>]*>/)
      if (parentMatch) {
        // 这是一个嵌套的ol，需要处理li的序号
        return content.replace(
          /<li[^>]*>(\d+)\.\s*/g,
          (liMatch, number) => {
            // 获取父级序号
            const parentNumber = getParentListNumber(match)
            return liMatch.replace(/\d+\.\s*/, `${parentNumber}.${number}. `)
          }
        )
      }
      return match
    }
  )
  
  return processedHtml
}

// 获取父级列表序号的辅助函数
const getParentListNumber = (html: string): string => {
  // 这里可以根据需要实现更复杂的逻辑来获取父级序号
  // 目前简单返回"1"作为默认值
  return "1"
}

// 处理嵌套的有序列表，确保子级使用正确的层级格式
const processNestedOrderedLists = (html: string): string => {
  // 使用DOM解析的方式处理嵌套列表
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = html
  
  // 递归处理嵌套的ol元素
  const processOlElement = (olElement: HTMLOListElement, parentNumber: string = '') => {
    const listItems = olElement.querySelectorAll('li')
    
    listItems.forEach((li, index) => {
      const currentNumber = index + 1
      const fullNumber = parentNumber ? `${parentNumber}.${currentNumber}` : `${currentNumber}`
      
      // 更新li的文本内容，替换开头的数字序号
      const textContent = li.textContent || ''
      const updatedText = textContent.replace(/^\d+\.\s*/, `${fullNumber}. `)
      li.textContent = updatedText
      
      // 递归处理嵌套的ol
      const nestedOl = li.querySelector('ol')
      if (nestedOl) {
        processOlElement(nestedOl, fullNumber)
      }
    })
  }
  
  // 处理所有顶级ol元素
  const topLevelOls = tempDiv.querySelectorAll('ol')
  topLevelOls.forEach(ol => {
    // 检查是否是顶级ol（不在其他ol内部）
    if (!ol.closest('li')) {
      processOlElement(ol)
    }
  })
  
  return tempDiv.innerHTML
}

// 智能内容渲染函数 - 处理混合HTML和Markdown内容
const getRenderedContent = (content: string): string => {
  if (!content) return ''
  
  // 检测是否包含HTML标签 - 更全面的检测
  const hasHtmlTags = /<[a-zA-Z][a-zA-Z0-9]*(?:\s+[^>]*)?>|<\/[a-zA-Z][a-zA-Z0-9]*>|<[a-zA-Z][a-zA-Z0-9]*\s*\/>/.test(content)
  
  // 检测是否包含Markdown语法
  const hasMarkdown = /#{1,6}\s+/.test(content) || /^\s*[-*]\s+/m.test(content) || /\*\*.*?\*\*/.test(content)
  
  console.log('内容检测调试:', {
    content: content.substring(0, 300),
    hasHtmlTags,
    hasMarkdown,
    htmlMatches: content.match(/<[a-zA-Z][a-zA-Z0-9]*(?:\s+[^>]*)?>|<\/[a-zA-Z][a-zA-Z0-9]*>|<[a-zA-Z][a-zA-Z0-9]*\s*\/>/g)
  })
  
  if (hasHtmlTags && hasMarkdown) {
    // 混合内容：既有HTML又有Markdown
    try {
      // 预处理：将<br/>转换为换行符，以便Markdown正确处理
      let processedContent = content.replace(/<br\s*\/?>/gi, '\n')
      
      // 使用marked渲染Markdown
      let html = marked.parse(processedContent) as string
      
      // 后处理：合并连续的有序列表
      html = mergeConsecutiveOrderedLists(html)
      html = processNestedOrderedLists(html)
      
      return html
    } catch (error) {
      console.error('混合内容渲染失败:', error)
      return content
    }
  } else if (hasHtmlTags) {
    // 纯HTML内容，直接返回
    return content
  } else if (hasMarkdown) {
    // 纯Markdown内容
    try {
      let processedContent = content.replace(/<br\s*\/?>/gi, '\n')
      let html = marked.parse(processedContent) as string
      html = mergeConsecutiveOrderedLists(html)
      html = processNestedOrderedLists(html)
      return html
    } catch (error) {
      console.error('Markdown渲染失败:', error)
      return content
    }
  } else {
    // 纯文本内容，将\n转换为<br/>以正确显示换行
    return content.replace(/\n/g, '<br/>')
  }
}

</script>

<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--minimal-bg);
}

.chat-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.chat-left {
  width: 300px;
  flex-shrink: 0;
  background: linear-gradient(135deg, #f8faff 0%, #f0f4ff 100%);
  border: 1px solid #e8f2ff;
  display: flex;
  flex-direction: column;
}

.knowledge-selector {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.knowledge-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.title-line {
  width: 4px;
  height: 20px;
  background: #6366f1;
  border-radius: 2px;
  margin-right: 12px;
}

.selection-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f1f5f9;
}

.select-all-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.select-all-checkbox {
  width: 16px;
  height: 16px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  flex-shrink: 0;
  background: white;
}

.select-all-checkbox:hover {
  border-color: #4f46e5;
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
}

.select-all-checkbox.checked {
  background: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.select-all-checkbox.checked:hover {
  background: #3730a3;
  border-color: #3730a3;
}

.select-all-checkbox .el-icon {
  font-size: 10px;
  font-weight: bold;
}

.select-all-text {
  font-size: 12px;
  color: #64748b;
  user-select: none;
}

.selected-count {
  font-size: 12px;
  color: #64748b;
  background: #f1f5f9;
  padding: 4px 8px;
  border-radius: 4px;
}

.clear-selection {
  font-size: 12px;
  color: #8b5cf6;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}

.clear-selection:hover:not(.disabled) {
  color: #7c3aed;
}

.clear-selection.disabled {
  color: #d1d5db;
  cursor: not-allowed;
}

/* 知识库Tab页样式 */
.knowledge-tabs {
  margin-bottom: 16px;
}

.tab-buttons {
  display: flex;
  background: #e8f2ff;
  border-radius: 8px;
  padding: 4px;
  gap: 2px;
}

.tab-button {
  flex: 1;
  padding: 8px 12px;
  border: none;
  background: transparent;
  color: #5b7cff;
  font-size: 13px;
  font-weight: 500;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.tab-button.active {
  background: white;
  color: #5b7cff;
  box-shadow: 0 1px 3px rgba(91, 124, 255, 0.2);
  font-weight: 600;
}

.tab-button:hover:not(.active) {
  background: rgba(255, 255, 255, 0.5);
}

.tab-badge {
  background: #5b7cff;
  color: white;
  font-size: 11px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.tab-button.active .tab-badge {
  background: #4f46e5;
}

/* 单一知识库类型指示器 */
.knowledge-type-indicator {
  padding: 8px 12px;
  background: linear-gradient(135deg, #f0f4ff 0%, #e8f2ff 100%);
  border: 1px solid #b3d8ff;
  border-radius: 8px;
  text-align: center;
}

.type-label {
  font-size: 14px;
  font-weight: 500;
  color: #5b7cff;
}

.knowledge-search {
  display: flex;
  gap: 8px
}

.knowledge-search-input {
  flex: 1;
  padding: 0px 5px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  outline: none;
}

.knowledge-search-btn {
  padding: 12px 16px;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background-color 0.2s ease;
}

.knowledge-search-btn:hover {
  background: #4f46e5;
}

.knowledge-search-btn.clear-btn {
  background: #f56565;
}

.knowledge-search-btn.clear-btn:hover {
  background: #e53e3e;
}

/* 知识库分类容器 */
.knowledge-categories {
  display: flex;
  flex-direction: column;
  gap: 16px;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  padding-right: 8px;
  height: calc(100vh - 200px);
  writing-mode: horizontal-tb;
  text-orientation: mixed;
}

.knowledge-categories * {
  writing-mode: horizontal-tb;
  text-orientation: mixed;
  word-break: keep-all;
}

.knowledge-categories::-webkit-scrollbar {
  width: 6px;
}

.knowledge-categories::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.knowledge-categories::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.knowledge-categories::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 一级分类容器 */
.knowledge-category {
  background: white;
  border-radius: 12px;
  overflow: visible;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  flex-shrink: 0;
}

/* 一级分类标题 */
.category-title {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #c7d2fe 0%, #a5b4fc 100%);
  font-weight: 500;
  color: #4338ca;
  font-size: 15px;
  cursor: pointer;
  border-radius: 12px 12px 0 0;
}

.category-title .expand-icon {
  margin-left: auto;
  transition: transform 0.3s ease;
  color: #4338ca;
}

.category-title .expand-icon.expanded {
  transform: rotate(90deg);
}

/* 分类列表容器 */
.category-list {
  padding: 0;
  background: white;
  border-radius: 0 0 12px 12px;
}

/* 分类项目基础样式 */
.category-item {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  border-bottom: 1px solid #f8fafc;
  white-space: nowrap;
  word-break: keep-all;
  writing-mode: horizontal-tb;
}

.category-item:hover {
  background-color: #f8fafc;
}

.category-item:last-child {
  border-bottom: none;
}

/* 复选框样式 */
.item-checkbox {
  width: 16px;
  height: 16px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  background: white;
  transition: all 0.2s ease;
}

.item-checkbox:hover {
  border-color: #4f46e5;
}

.item-checkbox.checked {
  background: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.item-checkbox.indeterminate {
  background: #f59e0b;
  border-color: #f59e0b;
  color: white;
}

.item-checkbox .el-icon {
  font-size: 10px;
  font-weight: bold;
}

/* 项目名称 */
.item-name {
  flex: 1;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: keep-all;
  writing-mode: horizontal-tb;
  text-orientation: mixed;
}

/* 展开图标 */
.expand-icon {
  margin-left: 8px;
  transition: transform 0.2s ease;
  cursor: pointer;
  flex-shrink: 0;
  color: #6b7280;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.chat-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  position: relative;
}

.chat-right.full-width {
  width: 100%;
  max-width: none;
}

/* 聊天工具栏 */
.chat-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  margin-top: 20px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.clear-btn {
  color: #dc3545;
  border-color: #dc3545;
}

.clear-btn:hover {
  background-color: #dc3545;
  border-color: #dc3545;
  color: white;
}

.chat-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.chat-welcome {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.welcome-avatar {
  width: 120px;
  height: 120px;
  margin-bottom: 24px;
  border-radius: 1rem;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(91, 124, 255, 0.2);
}

.avatar-gif {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.welcome-text h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #333;
}

.welcome-text p {
  margin: 0 0 24px 0;
  color: #666;
  font-size: 16px;
}

.quick-questions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 600px;
}

.question-row {
  display: flex;
  gap: 12px;
}

.quick-question {
  flex: 1;
  padding: 12px 20px;
  background: var(--minimal-primary-gradient);
  border: 1px solid transparent;
  border-radius: 8px;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.quick-question:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(91, 124, 255, 0.3);
}

.chat-input {
  width: 100%;
  margin-top: 20px;
  flex-shrink: 0;
}

.input-container {
  background: white;
  border-radius: 12px;
  border: 1px solid #e9ecef;
  overflow: hidden;
}

.input-container:has(.uploaded-files-inline) {
  border-radius: 0 0 12px 12px;
}

.input-container:has(.uploaded-files-inline) .input-wrapper {
  border-radius: 0 0 12px 12px;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
}

.message-input {
  border: none;
  outline: none;
  padding: 16px;
  font-size: 14px;
  resize: none;
  min-height: 40px;
  max-height: 120px;
  font-family: inherit;
  border-radius: 0;
}
.message {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
  margin: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar {
  background: var(--minimal-primary-gradient);
  color: white;
  font-weight: 600;
  font-size: 16px;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-gif {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 70%;
  position: relative;
}

.message-text {
  padding: 16px 20px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message.user .message-text {
  background: var(--minimal-primary-gradient);
  color: white;
  border-bottom-right-radius: 6px;
}

.message.assistant .message-text {
  background: #f1f3f5;
  color: #333;
  border-bottom-left-radius: 6px;
}

/* 消息格式化样式 */
.message-text :deep(.message-heading) {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #1f2937;
}

.message-text :deep(.message-h1) {
  font-size: 1.5em;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 8px;
}

.message-text :deep(.message-h2) {
  font-size: 1.3em;
  color: #374151;
}

.message-text :deep(.message-h3) {
  font-size: 1.1em;
  color: #4b5563;
}

.message-text :deep(.message-bold) {
  font-weight: 600;
  color: #1f2937;
}

.message-text :deep(.message-italic) {
  font-style: italic;
  color: #6b7280;
}

.message-text :deep(.message-code-block) {
  background: #1f2937;
  color: #f9fafb;
  padding: 12px;
  border-radius: 6px;
  margin: 8px 0;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.message-text :deep(.message-inline-code) {
  background: #e5e7eb;
  color: #1f2937;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.message-text :deep(.message-list-item) {
  display: flex;
  align-items: flex-start;
  margin: 4px 0;
  padding-left: 8px;
}

.message-text :deep(.message-list-number),
.message-text :deep(.message-list-bullet) {
  color: #5b7cff;
  font-weight: 600;
  margin-right: 8px;
  flex-shrink: 0;
}

.message-text :deep(.message-list-content) {
  flex: 1;
}

.message-text :deep(.message-link) {
  color: #5b7cff;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.2s ease;
}

.message-text :deep(.message-link:hover) {
  border-bottom-color: #5b7cff;
}

.message-text :deep(.message-quote) {
  border-left: 4px solid #5b7cff;
  background: #f0f4ff;
  padding: 8px 12px;
  margin: 8px 0;
  font-style: italic;
  color: #374151;
}

.message-text :deep(.message-divider) {
  border: none;
  height: 2px;
  background: linear-gradient(90deg, transparent, #e5e7eb, transparent);
  margin: 16px 0;
}

.message-text :deep(.message-table) {
  width: 100%;
  border-collapse: collapse;
  margin: 12px 0;
  background: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-text :deep(.message-table-header) {
  background: #f8f9fa;
}

.message-text :deep(.message-table-cell) {
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  text-align: left;
}

.message-text :deep(.message-table-header .message-table-cell) {
  font-weight: 600;
  color: #1f2937;
}
.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
}

.left-actions {
  display: flex;
  align-items: center;
}

.right-actions {
  display: flex;
  gap: 8px;
}

.upload-btn, .send-btn {
  padding: 8px 12px;
  border: 1px solid #e9ecef;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn {
  background: #6366f1;
  color: white;
  border-color: #6366f1;
}

.send-btn:disabled {
  background: #e9ecef;
  color: #adb5bd;
  border-color: #e9ecef;
  cursor: not-allowed;
}

.input-footer {
  text-align: center;
  margin-top: 12px;
}
.footer-text {
  font-size: 12px;
  color: #adb5bd;
}


.ai-status {
  display: flex;
  align-items: center;
  gap: 6px;
  background: rgba(91, 124, 255, 0.08);
  color: #5b7cff;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  margin-bottom: 12px;
  width: fit-content;
  border: 1px solid rgba(91, 124, 255, 0.15);
}

.ai-status.error,
.chat-page .ai-status.error,
.chat-main .ai-status.error {
  background: rgba(239, 68, 68, 0.08) !important;
  color: #ef4444 !important;
  border: 1px solid rgba(239, 68, 68, 0.15) !important;
}

.ai-status.thinking,
.chat-page .ai-status.thinking,
.chat-main .ai-status.thinking {
  background: rgba(255, 193, 7, 0.08) !important;
  color: #ffc107 !important;
  border: 1px solid rgba(255, 193, 7, 0.15) !important;
}

.ai-status.thinking .status-icon {
  animation: thinking-pulse 1.5s ease-in-out infinite;
}

@keyframes thinking-pulse {
  0%, 100% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.1);
  }
}

.status-icon {
  font-size: 10px;
  font-weight: bold;
}

.status-text {
  font-weight: 500;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 16px 20px;
  background: #f1f3f5;
  border-radius: 18px;
  border-bottom-left-radius: 6px;
  width: fit-content;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-6px);
    opacity: 1;
  }
}
.message-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  opacity: 1;
}

.action-btn {
  padding: 6px;
  background: rgba(0, 0, 0, 0.04);
  border: none;
  border-radius: 4px;
  color: #64748b;
  cursor: pointer;
  transition: all 0.15s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
}

.action-btn:hover {
  background: rgba(0, 0, 0, 0.08);
  color: #475569;
  transform: scale(1.05);
}

.action-btn.delete-btn:hover {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.action-btn.translated {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.action-btn.translated:hover {
  background: rgba(76, 175, 80, 0.2);
  color: #2e7d32;
}

/* 翻译状态指示器 */
.translation-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #4caf50;
  margin-bottom: 8px;
  padding: 4px 8px;
  background: rgba(76, 175, 80, 0.1);
  border-radius: 12px;
  width: fit-content;
}

.action-btn svg {
  width: 14px;
  height: 14px;
}

.uploaded-files {
  margin-top: 12px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  margin-bottom: 8px;
  border: 1px solid #e5e7eb;
}

.file-item:last-child {
  margin-bottom: 0;
}

.file-icon {
  color: #6b7280;
  flex-shrink: 0;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #9ca3af;
  flex-shrink: 0;
}

.remove-file {
  background: none;
  border: none;
  color: #ef4444;
  cursor: pointer;
  font-size: 18px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.remove-file:hover {
  background: rgba(239, 68, 68, 0.1);
}

/* 拖拽样式 */
.input-wrapper.drag-over {
  border-color: #4f46e5;
  background: rgba(79, 70, 229, 0.05);
}

/* 文件标签页样式 */
.uploaded-files-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 12px 16px 8px;
  border-bottom: none;
  border-radius: 12px 12px 0 0;
}

.file-tab {
  display: flex;
  align-items: center;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 8px 8px 0 0;
  padding: 8px 12px;
  max-width: 280px;
  min-width: 200px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
}

.file-tab:hover {
  border-color: #9ca3af;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.file-tab-icon {
  flex-shrink: 0;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.file-tab-content {
  flex: 1;
  min-width: 0;
  margin-right: 8px;
}

.file-tab-title {
  font-size: 13px;
  font-weight: 500;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.file-tab-url {
  font-size: 11px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
  margin-top: 2px;
}

.file-tab-close {
  flex-shrink: 0;
  background: none;
  border: none;
  color: #9ca3af;
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.file-tab-close:hover {
  background: #f3f4f6;
  color: #6b7280;
}

.file-tab-close:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 文件上传状态样式 */
.file-tab.uploading {
  border-color: #ffc107;
  background: rgba(255, 193, 7, 0.05);
}

.uploading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-status {
  font-size: 11px;
  font-weight: 500;
  color: #6b7280;
}

.upload-status.success {
  color: #28a745;
}

.upload-status.error {
  color: #dc3545;
}

/* 搜索来源样式 */
.search-sources {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 12px;
  border: 1px solid #e8f2ff;
}

.sources-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #5b7cff;
}

.sources-title {
  color: #5b7cff;
}

.sources-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 12px;
}

.source-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  border: 1px solid #e8f2ff;
  transition: all 0.2s ease;
  cursor: pointer;
}

.source-card:hover {
  border-color: #5b7cff;
  box-shadow: 0 2px 8px rgba(91, 124, 255, 0.1);
  transform: translateY(-1px);
}

.source-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.source-title {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  flex: 1;
  margin-right: 8px;
}

.source-category {
  font-size: 11px;
  padding: 2px 6px;
  background: #e8f2ff;
  color: #5b7cff;
  border-radius: 4px;
  white-space: nowrap;
}

.source-content {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
  line-height: 1.3;
}

.source-url {
  font-size: 11px;
  color: #999;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 企业知识库来源样式 */
.source-card.enterprise-source {
  border-left: 3px solid #1890ff;
  background: linear-gradient(135deg, #f6f9ff 0%, #e8f4ff 100%);
}

.source-card.enterprise-source:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

.source-category.enterprise-category {
  background: #e8f4ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

/* 个人知识库来源样式 */
.source-card.personal-source {
  border-left: 3px solid #52c41a;
  background: linear-gradient(135deg, #f6ffed 0%, #e6f7d6 100%);
}

.source-card.personal-source:hover {
  border-color: #52c41a;
  box-shadow: 0 2px 8px rgba(82, 196, 26, 0.15);
}

.source-category.personal-category {
  background: #e6f7d6;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

/* 消息中的文件标签页样式 */
.message-files {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.message-file-tab {
  display: flex;
  align-items: center;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  padding: 8px 12px;
  max-width: 280px;
  min-width: 200px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-file-tab:hover {
  border-color: #9ca3af;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.message-file-icon {
  flex-shrink: 0;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

.message-file-content {
  flex: 1;
  min-width: 0;
  margin-right: 8px;
}

.message-file-title {
  font-size: 13px;
  font-weight: 500;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.message-file-url {
  font-size: 11px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
  margin-top: 2px;
}

.message-file-size {
  flex-shrink: 0;
  font-size: 11px;
  color: #9ca3af;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
}
/* 层级分类样式 */
.category-item-wrapper {
  width: 100%;
}

.category-item {
  display: flex;
  align-items: center;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  border-bottom: 1px solid #f8fafc;
  white-space: nowrap;
  word-break: keep-all;
  writing-mode: horizontal-tb;
  padding: 8px 20px;
}

.category-item:hover {
  background-color: #f8fafc;
}

/* 动态层级缩进 */
.category-item.level-1 { padding-left: 40px; font-weight: 500; }
.category-item.level-2 { padding-left: 60px; font-size: 13px; color: #6b7280; }
.category-item.level-3 { padding-left: 80px; font-size: 12px; color: #9ca3af; }
.category-item.level-4 { padding-left: 100px; font-size: 11px; color: #9ca3af; }
.category-item.level-5 { padding-left: 120px; font-size: 10px; color: #9ca3af; }
.category-item.level-6 { padding-left: 140px; font-size: 10px; color: #9ca3af; }
.category-item.level-7 { padding-left: 160px; font-size: 9px; color: #9ca3af; }
.category-item.level-8 { padding-left: 180px; font-size: 9px; color: #9ca3af; }

/* 复选框样式 */
.item-checkbox {
  width: 16px;
  height: 16px;
  border: 2px solid #d1d5db;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
  background: white;
  transition: all 0.2s ease;
}

.item-checkbox:hover {
  border-color: #4f46e5;
}

.item-checkbox.checked {
  background: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.item-checkbox.indeterminate {
  background: #f59e0b;
  border-color: #f59e0b;
  color: white;
}

.item-checkbox .el-icon {
  font-size: 10px;
  font-weight: bold;
}

/* 层级复选框大小调整 */
.level-2 .item-checkbox {
  width: 14px;
  height: 14px;
}

.level-3 .item-checkbox {
  width: 12px;
  height: 12px;
}

.level-4 .item-checkbox {
  width: 10px;
  height: 10px;
}

.item-name {
  flex: 1;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: keep-all;
  writing-mode: horizontal-tb;
  text-orientation: mixed;
}

.expand-icon {
  margin-left: 8px;
  transition: transform 0.2s ease;
  cursor: pointer;
  flex-shrink: 0;
  color: #6b7280;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

/* Markdown 内容样式 */
.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3),
.message-text :deep(h4),
.message-text :deep(h5),
.message-text :deep(h6) {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #1f2937;
}

.message-text :deep(h1) { font-size: 24px; }
.message-text :deep(h2) { font-size: 20px; }
.message-text :deep(h3) { font-size: 18px; }
.message-text :deep(h4) { font-size: 16px; }
.message-text :deep(h5) { font-size: 14px; }
.message-text :deep(h6) { font-size: 12px; }

.message-text :deep(p) {
  margin: 8px 0;
  line-height: 1.6;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.message-text :deep(li) {
  margin: 4px 0;
}

.message-text :deep(blockquote) {
  margin: 12px 0;
  padding: 8px 16px;
  background: #f8f9fa;
  border-left: 4px solid #6b7280;
  border-radius: 4px;
}

.message-text :deep(code) {
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  color: #dc2626;
}

.message-text :deep(pre) {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid #e5e7eb;
}

.message-text :deep(pre code) {
  background: transparent;
  padding: 0;
  color: #374151;
  font-size: 13px;
  line-height: 1.5;
}

.message-text :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 12px 0;
  font-size: 13px;
}

.message-text :deep(th),
.message-text :deep(td) {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
  text-align: left;
}

.message-text :deep(th) {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.message-text :deep(a) {
  color: #3b82f6;
  text-decoration: none;
}

.message-text :deep(a:hover) {
  text-decoration: underline;
}

.message-text :deep(strong) {
  font-weight: 600;
  color: #1f2937;
}

.message-text :deep(em) {
  font-style: italic;
}

.message-text :deep(hr) {
  margin: 16px 0;
  border: none;
  height: 1px;
  background: #e5e7eb;
}

/* 强化Markdown样式 - 确保优先级 */
.message-text :deep(h1),
.message-text :deep(h2), 
.message-text :deep(h3) {
  margin: 16px 0 8px 0 !important;
  font-weight: 600 !important;
  color: #1f2937 !important;
  line-height: 1.4 !important;
}

.message-text :deep(h1) { 
  font-size: 24px !important; 
}

.message-text :deep(h2) { 
  font-size: 20px !important; 
}

.message-text :deep(h3) { 
  font-size: 18px !important; 
}

.message-text :deep(ol),
.message-text :deep(ul) {
  margin: 12px 0 !important;
  padding-left: 24px !important;
}

.message-text :deep(ol) {
  list-style: decimal !important;
  counter-reset: item !important;
}

.message-text :deep(ol li) {
  margin: 6px 0 !important;
  padding-left: 8px !important;
  list-style: decimal !important;
}

.message-text :deep(ol li::marker) {
  color: #5b7cff !important;
  font-weight: 600 !important;
}

.message-text :deep(ul li) {
  margin: 6px 0 !important;
  position: relative !important;
}
/* 
.message-text :deep(ul li)::before {
  content: "• " !important;
  color: #5b7cff !important;
  font-weight: 600 !important;
  position: absolute !important;
  left: -16px !important;
} */

.message-text :deep(p) {
  margin: 8px 0 !important;
  line-height: 1.6 !important;
}

.message-text :deep(strong) {
  font-weight: 600 !important;
  color: #1f2937 !important;
}
</style>

<style>
/* 最高优先级的样式覆盖 */
:deep(.el-button--primary) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus),
:deep(.el-button--primary:active) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

/* 搜索来源下拉框样式 */
.search-source-select {
  border-radius: 6px;
  font-size: 12px;
}

.search-source-select .el-input__inner {
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  border-radius: 6px;
}

.search-source-select .el-input__suffix {
  height: 28px;
  line-height: 28px;
}

.search-source-select .el-select__caret {
  line-height: 28px;
}

/* 扩写和简写内容样式 */
.expanded-content,
.summarized-content {
  margin-top: 16px;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid;
}

.expanded-content {
  background: #f0f9ff;
  border-left-color: #10b981;
}

.summarized-content {
  background: #fffbeb;
  border-left-color: #f59e0b;
}

.expanded-header,
.summarized-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  font-size: 14px;
}

.expanded-header {
  color: #065f46;
}

.summarized-header {
  color: #92400e;
}

.expanded-text,
.summarized-text {
  line-height: 1.6;
  color: #374151;
}

.expanded-text :deep(p),
.summarized-text :deep(p) {
  margin: 8px 0;
}

.expanded-text :deep(ul),
.summarized-text :deep(ul) {
  margin: 8px 0;
  padding-left: 20px;
}

.expanded-text :deep(li),
.summarized-text :deep(li) {
  margin: 4px 0;
}

/* Mermaid图表样式 */
.mermaid-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 16px 0;
  padding: 16px;
  background: #fafbff;
  border: 1px solid #e8f2ff;
  border-radius: 8px;
  overflow-x: auto;
}

.mermaid-container svg {
  max-width: 100%;
  height: auto;
  background: transparent;
}

.mermaid-error {
  margin: 16px 0;
  padding: 16px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 8px;
  color: #ff4d4f;
}

.mermaid-error p {
  margin: 0 0 8px 0;
  font-weight: 600;
}

.mermaid-error pre {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  margin: 0;
  overflow-x: auto;
}

.mermaid-error code {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #666;
}

/* 来源信息样式 */
.source-info {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
}
/* 
.source-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
} */

.source-item:last-child {
  margin-bottom: 0;
}

.source-label {
  font-weight: 600;
  color: #495057;
  min-width: 80px;
  flex-shrink: 0;
  margin-right: 8px;
}

.source-value {
  color: #6c757d;
  flex: 1;
  word-break: break-all;
}

.source-image {
  max-width: 200px;
  max-height: 150px;
  margin: 4px 8px 4px 0;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.source-image:hover {
  transform: scale(1.05);
}

</style>
